leetcode解题: Flatten Binary Tree to Linked List (114)

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

解法1: Divide & Conquer

思路是对于每一个节点,如果有left和right两个child, 对left和right分别做flatten的话,只需要把left的child和right的root相连,同时把left的root设为NULL. 然后把root和left的root相连就得到了flatten的list。
具体实现起来的时候,可以建立一个辅助的struct来存储每一个节点对应的flatten之后的root和child。
C++

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct NodePair {
TreeNode* root;
TreeNode* child;
NodePair(TreeNode* r, TreeNode* c):root(r),child(c) {}
};
class Solution {
public:
void flatten(TreeNode* root) {
if (!root) {
return;
}
NodePair res = helper(root);
}
NodePair helper(TreeNode* root) {
if (!root) {
return NodePair(NULL, NULL);
}
if (!root->left && !root->right) {
return NodePair(root, root);
}
NodePair left = helper(root->left);
NodePair right = helper(root->right);
// Combine
root->left = NULL;
if (!left.root) {
root->right = right.root;
} else {
root->right = left.root;
left.child->left = NULL;
left.child->right = right.root;
}
return NodePair(root, right.child?right.child:left.child);
}
};

Java

1

解法2: Preorder traversal

从给的例子可以看到,最后的顺序是一个preorder traversal。 那么我们可以先进行preorder, 然后把vector中的node都连接起来。
C++

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
class Solution {
public:
void flatten(TreeNode* root) {
if (!root) {
return;
}
vector<TreeNode*> nodes;
preorder(nodes, root);
for (int i = 0; i < nodes.size() - 1; ++i) {
nodes[i]->left = NULL;
nodes[i]->right = nodes[i + 1];
}
nodes[nodes.size() - 1]->left = nodes[nodes.size() - 1]->right = NULL;
return;
}
void preorder(vector<TreeNode*>& nodes, TreeNode* root) {
if (!root) {
return;
}
nodes.push_back(root);
preorder(nodes, root->left);
preorder(nodes, root->right);
}
};

解法3: Iterative

基本思想就是从上往下,如果有left child就把最右端的接到right child上,然后把left child移到左边。然后再按照路劲往下一个node,也就是说root = root.right

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void flatten(TreeNode root) {
if (root == null) return;
while (root != null) {
if (root.left != null) {
TreeNode prev = root.left;
while (prev.right != null) {
prev = prev.right;
}
prev.right = root.right;
root.right = root.left;
root.left = null;
}
root = root.right; // go down along the path
}
}
}