Skip to content

Commit dd3054b

Browse files
committed
Added to Trees
1 parent d151353 commit dd3054b

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Src : LeetCode
3+
--------------
4+
5+
Given the root of a binary tree, flatten the tree into a "linked list":
6+
7+
1) The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
8+
2) The "linked list" should be in the same order as a pre-order traversal of the binary tree.
9+
10+
Input: root = [1,2,5,3,4,null,6]
11+
Output: [1,null,2,null,3,null,4,null,5,null,6]
12+
*/
13+
14+
/**
15+
* Definition for a binary tree node.
16+
* struct TreeNode {
17+
* int val;
18+
* TreeNode *left;
19+
* TreeNode *right;
20+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
21+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
22+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
23+
* };
24+
*/
25+
class Solution {
26+
public:
27+
TreeNode* flattenSubtrees(TreeNode* root){
28+
if(!root->left && !root->right) return root;
29+
if(root->left==NULL)
30+
return fun(root->right);
31+
TreeNode* last=fun(root->left);
32+
last->right=root->right;
33+
root->right=root->left;
34+
root->left=NULL;
35+
return fun(last);
36+
}
37+
38+
void flatten(TreeNode* root) {
39+
if(!root) return;
40+
flatten(root->left);
41+
flatten(root->right);
42+
TreeNode* right=root->right;
43+
root->right=root->left;
44+
root->left=NULL;
45+
TreeNode* cur=root;
46+
while(cur->right){
47+
cur=cur->right;
48+
}
49+
cur->right=right;
50+
51+
}
52+
};

0 commit comments

Comments
 (0)