-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution_114.java
More file actions
78 lines (76 loc) · 1.99 KB
/
Solution_114.java
File metadata and controls
78 lines (76 loc) · 1.99 KB
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
/*
114. 二叉树展开为链表
给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
*/
/*
交换左右子树,深度优先遍历右子树,然后把左子树放到右子树叶子节点后,清空左子树,继续遍历
*/
class Solution {
public static void main(String[] args) {
TreeNode[] n = new TreeNode[]{
new TreeNode(1),
new TreeNode(2),
new TreeNode(3),
new TreeNode(4),
new TreeNode(5),
new TreeNode(6),
new TreeNode(7),
new TreeNode(8),
new TreeNode(9),
new TreeNode(10)
};
n[0].left = n[1]; n[0].right = n[2];
n[1].left = n[3]; n[1].right = n[4];
n[2].left = n[5]; n[2].right = n[6];
n[6].right = n[7]; n[7].right = n[8];
n[8].right = n[9];
Solution solution = new Solution();
solution.flatten(n[0]);
TreeNode N = n[0];
while ( N != null ) {
System.out.print(N.val+" ");
N = N.right;
}
}
public void flatten(TreeNode root) {
if ( root == null ) return ;
if ( root.left != null ) {
if ( root.right == null ) {
root.right = root.left;
root.left = null;
flatten(root.right);
} else {
TreeNode temp = root.right;
root.right = root.left;
root.left = temp;
flatten(root.right);
temp = root.right;
while ( temp.right != null ) temp = temp.right;
temp.right = root.left;
root.left = null;
flatten(temp.right);
}
} else {
if ( root.right != null)
flatten(root.right);
}
}
}