LeetCode: Populating Next Right Pointers in Each Node

LeetCode: Populating Next Right Pointers in Each Node

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

/**
* Created by hzhou on 4/27/15. [email protected]
*/
public class PopulatingNextRightPointersInEachNode {
public void connect(TreeLinkNode root) {
if (root == null) {
return;
}
Stack<TreeLinkNode> stack = new Stack<TreeLinkNode>();
stack.push(root);
while (!stack.isEmpty()) {
TreeLinkNode node = stack.pop();
if (node.left != null) {
stack.push(node.left);
TreeLinkNode cursor = null;
while (node != null) {
if (cursor != null) {
cursor.next = node.left;
}
node.left.next = node.right;
cursor = node.right;
node = node.next;
}
}
}
}
}