@@ -30,12 +30,42 @@ class Solution {
30
30
tree_stack.push (node->left );
31
31
node->left = NULL ;
32
32
}
33
- if (flatten_node == NULL )
33
+ if (flatten_node == NULL ) {
34
34
flatten_node = node;
35
- else {
35
+ } else {
36
36
flatten_node->right = node;
37
37
flatten_node = flatten_node->right ;
38
38
}
39
39
}
40
40
}
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