Skip to content

Commit b04aafa

Browse files
Create convert_binary_tree_to_linked_list.cpp
1 parent dbe7caf commit b04aafa

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
void flatten(TreeNode* root) {
15+
/*
16+
17+
1 1 1
18+
/\ / \ \
19+
2 5 => 2 5 =>. 2
20+
/ \ \ \ \ \
21+
3 4 6 3 6 3
22+
\ \
23+
4 4
24+
\
25+
5
26+
\
27+
6
28+
In the above problem, we have to traverse in preorder fashion and change left subtree to right subtree. Once we do that, we have to fix the right subtree below the changed left subtree.
29+
*/
30+
31+
32+
33+
if(!root or (!root->left and !root->right)) return; //important to traverse back from leaf node to the parent node.
34+
35+
if(root->left) { //check first if we have a left subtree from current root
36+
37+
flatten(root->left); //recurse until the leftmost child in current tree
38+
39+
TreeNode *tempRight = root->right; //store the right child of original tree into a temporary variable
40+
41+
root->right = root->left; //stick left half to right half(check node 3, 4 in diagram)
42+
root->left = NULL; //set the left of original tree to NULL
43+
44+
TreeNode *current = root->right; //stick right half of original tree(tempRight) below new right subtree
45+
while(current->right != NULL) {
46+
current = current->right;
47+
}
48+
49+
current->right = tempRight;
50+
}
51+
52+
flatten(root->right);
53+
}
54+
};

0 commit comments

Comments
 (0)