-
-
Notifications
You must be signed in to change notification settings - Fork 609
/
Copy pathFlattenBinaryTreetoLinkedList.java
62 lines (53 loc) · 1.5 KB
/
FlattenBinaryTreetoLinkedList.java
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
package problems.medium;
import problems.utils.TreeNode;
/**
* Created by sherxon on 1/3/17.
*/
public class FlattenBinaryTreetoLinkedList {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(5);
root.right.right = new TreeNode(6);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(4);
new FlattenBinaryTreetoLinkedList().flatten2(root);
}
public void flatten2(TreeNode root) {
if (root == null)
return;
flatten2(root.left);
flatten2(root.right);
TreeNode left = root.left;
root.left = null;
if (left != null) {
TreeNode t = left;
while (t.right != null)
t = t.right;
t.right = root.right;
root.right = left;
}
}
public void flatten(TreeNode root) {
if (root == null) return;
f(root);
reverse(root);
}
void reverse(TreeNode root) {
if (root == null) return;
reverse(root.left);
root.right = root.left;
root.left = null;
}
void f(TreeNode x) {
while (x != null) {
TreeNode l = x.left;//left Largest
while (l != null && l.right != null)
l = l.right;
if (l == null) x.left = x.right;
else l.right = x.right;
x.right = null;
x = x.left;
}
}
}