Leetcode(114) Flatten Binary Tree to Linked List

Description

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

For example, given the following tree:

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

解法

刚开始没弄明白原地展开是什么鬼,意思是把树的左边往右边合并,思路是递归地解决问题,采用头递归地写法更好理解,首先对跟节点的左右子树分别递归地进行展开,得到的情况如下图所示:

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

之后在把根的左子树设为空,并找到原左子树的最下节点与右子树接上即可。

具体代码如下:

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
/**
* 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;
}
if(root.left != null){
flatten(root.left);
}
if(root.right != null){
flatten(root.right);
}
TreeNode tmp = root.right;
root.right = root.left;
root.left = null;
while(root.right != null){
root = root.right;
}
root.right = tmp;
}

}