116 Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node

1. Question

Given a binary tree
1
struct TreeLinkNode {
2
TreeLinkNode *left;
3
TreeLinkNode *right;
4
TreeLinkNode *next;
5
}
Copied!
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL.
Initially, all next pointers are set toNULL.
Note:
  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example, Given the following perfect binary tree,
1
1
2
/ \
3
2 3
4
/ \ / \
5
4 5 6 7
Copied!
After calling your function, the tree should look like:
1
1 ->NULL
2
/ \
3
2 -> 3 ->NULL
4
/ \ / \
5
4->5->6->7 ->NULL
Copied!

2. Implementation

(1) Recursion
1
public class Solution {
2
public void connect(TreeLinkNode root) {
3
if (root == null) {
4
return;
5
}
6
7
if (root.left != null) {
8
root.left.next = root.right;
9
if (root.next != null && root.right != null) {
10
root.right.next = root.next.left;
11
}
12
}
13
14
connect(root.left);
15
connect(root.right);
16
}
17
}
Copied!
(2) Iteration
1
public class Solution {
2
public void connect(TreeLinkNode root) {
3
if (root == null) {
4
return;
5
}
6
7
TreeLinkNode curNode = root;
8
TreeLinkNode leftMostNode = null;
9
10
while (curNode.left != null) {
11
leftMostNode = curNode.left;
12
while (curNode != null) {
13
curNode.left.next = curNode.right;
14
curNode.right.next = curNode.next == null ? null : curNode.next.left;
15
curNode = curNode.next;
16
}
17
curNode = leftMostNode;
18
}
19
}
20
}
Copied!

3. Time & Space Complexity

Recursion: 时间复杂度: O(n), 空间复杂度: O(h)
Iteration: 时间复杂度: O(n), 空间复杂度: O(1)