- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlattenBinaryTree.java
More file actions
Latest commit
60 lines (54 loc) · 1.61 KB
/
Copy pathFlattenBinaryTree.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
importjava.util.LinkedList;
importjava.util.Queue;
importjava.util.Stack;
publicclassFlattenBinaryTree {
publicstaticvoidflatten(TreeNoderoot) {
if(root == null || root.left == null && root.right == null) return;
Stack<TreeNode> stack = newStack<TreeNode>();
Queue<TreeNode> queue = newLinkedList<TreeNode>();
stack.push(root);
queue.offer(root);
TreeNodetmp = root;
while(!stack.isEmpty()) {
if(tmp != null && tmp.left != null) {
tmp = tmp.left;
stack.push(tmp);
queue.offer(tmp);
} elseif(tmp != null && tmp.right != null){
tmp = tmp.right;
stack.push(tmp);
queue.offer(tmp);
} else {
tmp = stack.pop().right;
}
}
TreeNodeprev = 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;
}
publicstaticvoidmain(String[] args) {
TreeNodea = newTreeNode(1);
TreeNodeb = newTreeNode(2);
TreeNodec = newTreeNode(3);
TreeNoded = newTreeNode(4);
TreeNodee = newTreeNode(5);
TreeNodef = newTreeNode(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;
}
}
}