-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlattenBinaryTree.java
More file actions
60 lines (54 loc) · 1.61 KB
/
FlattenBinaryTree.java
File metadata and controls
60 lines (54 loc) · 1.61 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
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class FlattenBinaryTree {
public static void flatten(TreeNode root) {
if(root == null || root.left == null && root.right == null) return;
Stack<TreeNode> stack = new Stack<TreeNode>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
stack.push(root);
queue.offer(root);
TreeNode tmp = root;
while(!stack.isEmpty()) {
if(tmp != null && tmp.left != null) {
tmp = tmp.left;
stack.push(tmp);
queue.offer(tmp);
} else if(tmp != null && tmp.right != null){
tmp = tmp.right;
stack.push(tmp);
queue.offer(tmp);
} else {
tmp = stack.pop().right;
}
}
TreeNode prev = queue.poll();
tmp = queue.poll();
while(!queue.isEmpty()) {
prev.right = tmp;
prev.left = null;
prev = tmp;
tmp = queue.poll();
}
prev.left = null;
prev.right = tmp;
}
public static void main(String[] args) {
TreeNode a = new TreeNode(1);
TreeNode b = new TreeNode(2);
TreeNode c = new TreeNode(3);
TreeNode d = new TreeNode(4);
TreeNode e = new TreeNode(5);
TreeNode f = new TreeNode(6);
a.left = b;
a.right = e;
b.left = c;
b.right = d;
e.right = f;
flatten(a);
while(a != null) {
System.out.println(a.val);
a = a.right;
}
}
}