Star

LeetCode 114. Flatten Binary Tree to Linked List

Question

Given a binary tree, flatten it to a linked list in-place.

For example, Given

1
2
3
4
5
1
/ \
2 5
/ \ \
3 4 6

The flattened tree should look like:

1
2
3
4
5
6
7
8
9
10
11
1
\
2
\
3
\
4
\
5
\
6

Explanation

分治法,左右子树递归以后,把左右根节点依次排到右边,左边为空即可。

Code

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