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
public class Solution {
public void connect(TreeLinkNode root) {
Queue<TreeLinkNode> queue = new LinkedList<>();
if(root==null) return;
queue.offer(root);
while(!queue.isEmpty()){
int len = queue.size();
while(len-->0){
TreeLinkNode temp = queue.poll();
if(len==0) temp.next = null;
else temp.next = queue.peek();
if(temp.left!=null) queue.offer(temp.left);
if(temp.right!=null) queue.offer(temp.right);
}
}
}
}
忘了只能用常数空间。。。
参考别人的做法,保存每层的第一个和前一个
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) {
while (cur != null) { //iterate on the current level
//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;
}
}
}