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
Solution:Iterative 每层遍历
思路:Iterative 每层遍历,再遍历同层上各子树block,并keep一个prev用来连接
Time Complexity: O(N) Space Complexity: O(1)
Solution Code:
public class Solution {
//based on level order traversal
public void connect(TreeLinkNode root) {
TreeLinkNode head = null; //head of the next level
TreeLinkNode prev = null; //the leading node on the next level
TreeLinkNode cur = root; //current node of current level
while (cur != null) { // iterate on next level
while (cur != null) { //iterate on the current level, different blocks
//left child
if (cur.left != null) {
if (prev != null) {
prev.next = cur.left;
} else {
head = cur.left;
}
prev = cur.left;
}
//right child
if (cur.right != null) {
if (prev != null) {
prev.next = cur.right;
} else {
head = cur.right;
}
prev = cur.right;
}
//move to next node
cur = cur.next;
}
//move to next level
cur = head;
head = null;
prev = null;
}
}
}
Solution Code Round1
public class Solution {
public void connect(TreeLinkNode root) {
TreeLinkNode next_l_head = null;
TreeLinkNode prev = null;
TreeLinkNode post = null;
TreeLinkNode cur = root;
while(cur != null) { // different level
while(cur != null) { // different nodes on same level
// left child
if(cur.left != null) {
post = cur.left;
if(prev != null) prev.next = post;
else next_l_head = post;
prev = post;
}
// right child
if(cur.right != null) {
post = cur.right;
if(prev != null) prev.next = post;
else next_l_head = post;
prev = post;
}
// move to next node
cur = cur.next;
}
// move to next level
cur = next_l_head;
next_l_head = null;
prev = null;
}
}
}