Skip to content

Commit 50c2795

Browse files
committed
2
1 parent 31d467d commit 50c2795

File tree

1 file changed

+33
-3
lines changed

1 file changed

+33
-3
lines changed

FlattenBinaryTreetoLinkedList/FlattenBinaryTreetoLinkedList.cpp

+33-3
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,42 @@ class Solution {
3030
tree_stack.push(node->left);
3131
node->left = NULL;
3232
}
33-
if (flatten_node == NULL)
33+
if (flatten_node == NULL) {
3434
flatten_node = node;
35-
else {
35+
} else {
3636
flatten_node->right = node;
3737
flatten_node = flatten_node->right;
3838
}
3939
}
4040
}
41-
};
41+
};
42+
43+
// recursion
44+
class Solution {
45+
public:
46+
void flatten(TreeNode *root) {
47+
dfs(root);
48+
}
49+
50+
pair<TreeNode*, TreeNode*> dfs(TreeNode* root) {
51+
if (root == NULL) {
52+
return make_pair((TreeNode*)NULL, (TreeNode*)NULL);
53+
}
54+
pair<TreeNode*, TreeNode*> left = dfs(root->left);
55+
pair<TreeNode*, TreeNode*> right = dfs(root->right);
56+
root->left = NULL;
57+
root->right = NULL;
58+
if (left.first && right.first) {
59+
root->right = left.first;
60+
left.second->right = right.first;
61+
return make_pair(root, right.second);
62+
} else if (left.first) {
63+
root->right = left.first;
64+
return make_pair(root, left.second);
65+
} else if (right.first) {
66+
root->right = right.first;
67+
return make_pair(root, right.second);
68+
}
69+
return make_pair(root, root);
70+
}
71+
};

0 commit comments

Comments
 (0)