leetcode解题: Populating next right pointers in each node II (117)

Follow up for problem “Populating Next Right Pointers in Each Node”.

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

You may only use constant extra space.
For example,
Given the following binary tree,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL

解法1: BFS, O(N) Time + O(N) Space

运用此前perfect tree的解法,此题任然有效。
C++

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
void connect(TreeLinkNode *root) {
if (!root) {
return;
}
queue<TreeLinkNode*> q;
q.push(root);
while(!q.empty()) {
int number = q.size();
TreeLinkNode* prev = NULL;
for (int i = 0; i < number; ++i) {
TreeLinkNode* cur = q.front();
q.pop();
cur->next = prev;
prev = cur;
if (cur->right) {
q.push(cur->right);
}
if (cur->left) {
q.push(cur->left);
}
}
}
return;
}

Java

1

解法2: Iterative, O(N) Time + O(1) Space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution {
public void connect(TreeLinkNode root) {
TreeLinkNode dummy = new TreeLinkNode(0); // point to the next level's first node
TreeLinkNode prev = dummy;
while (root != null) {
if (root.left != null) {
prev.next = root.left;
prev = prev.next;
}
if (root.right != null) {
prev.next = root.right;
prev = prev.next;
}
root = root.next;
if (root == null) {
// end of current level, move to the next level
root = dummy.next;
prev = dummy;
dummy.next = null;
}
}
}
}