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 每層遍歷嗡官,再遍歷同層上各子樹(shù)block葱蝗,并keep一個(gè)prev用來(lái)連接
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;
}
}
}