-
Notifications
You must be signed in to change notification settings - Fork 0
/
Flatten_binary_tree_to_linked_list
88 lines (83 loc) · 2.24 KB
/
Flatten_binary_tree_to_linked_list
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void flatten(TreeNode *root) {
if (root==NULL) return;
if (root->left==NULL) flatten(root->right);
else
{
TreeNode *nd=root->left, *right=root->right;
//get the right most node in the left branch of root
while(nd->right!=NULL)
{
nd=nd->right;
}
root->right=root->left;
root->left=NULL;
nd->right=right;
root=root->right;
flatten(root);
}
}
};
REMARK:
1. Hard one.
IDEA:(refer to http://yucoding.blogspot.com/2013/01/leetcode-question-30-flatten-binary.html)
The flatten procedure is like: cut the left child and set to right, the right child is then linked to somewhere behind the left child. Where should it be then? Actually the right child should be linked to the most-right node of the left node.
So the algorithm is as follows:
(1) store the right child (we call R)
(2) find the right-most node of left child
(3) set R as the right-most node's right child.
(4) set left child as the right child
(5) set the left child NULL
(6) set current node to current node's right child.
(7) iterate these steps until all node are flattened.
2 Another version use the same idea without recursion:
class Solution {
public:
void flatten(TreeNode *root) {
while (root){
if (root->left){
TreeNode* pre=root->left;
while (pre->right){pre = pre->right;}
pre->right = root->right;
root->right = root->left;
root->left = NULL;
}
root=root->right;
}
}
};