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
這道題的關鍵點在于維系三個 變量:
- curt : the curt root we are passing as the method argument
- first : the first node in the level same as root's children'
- prev : the previous node we just connected to its next node in this level
每次循環要先確定first, 因為每次我們換行都會更新first為null, 所以要首先定下來新的first. 然后我們分別查看curt.left, curt.right, 如果左子樹不為空,我們就要把之前剛連接好的node的next指向curt.left. 也就是prev.next = curt.left. 然而要這么做,我們必須先判斷curt.left != null, 并且要注意prev == null 和prev != null兩種情況。第一種情況說明這一層還沒開始連next node, 那么直接設prev = curt.left就好了,;另一種情況就要連接之前連接的最后一個節點和目前的節點,即prev.next = curt.left. 右子樹同理。最后連接完左右子樹后,要確定curt所在level還有其他節點么,也就是curt.next == null? 如果沒有了,則開始下一行的連接,更新curt, first, prev就可以了;如果還有,直接curt = curt.next 接著連接下一個。
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if (root == null){
return;
}
TreeLinkNode curt = root;
//the first node in the level where the children of root are
TreeLinkNode first = null;
//the last node finished connecting to its next in this level
//(the same level as root's childreb).
TreeLinkNode prev = null;
while (curt != null){
if (first == null){
if (curt.left != null){
first = curt.left;
} else if (curt.right != null){
first = curt.right;
}
}
if (curt.left != null){
if (prev != null){
prev.next = curt.left;
}
prev = curt.left;
}
if (curt.right != null){
if (prev != null){
prev.next = curt.right;
}
prev = curt.right;
}
if (curt.next != null){
curt = curt.next;
} else {
curt = first;
prev = null;
first = null;
}
}
}
}