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
采用层次遍历的方法,对每一层进行操作,同时在操作该层时记下下一层节点的数目
/**
* 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;
int thislevel = 1;
int nextlevel = 0;
LinkedList<TreeLinkNode> q = new LinkedList<TreeLinkNode>();
q.add(root);
while(q.isEmpty() == false) {
while(thislevel > 0) {
TreeLinkNode temp = q.poll();
thislevel--;
if (thislevel == 0) temp.next = null;
else temp.next = q.peek();
if(temp.left != null) {
nextlevel++;
q.offer(temp.left);
}
if(temp.right != null) {
nextlevel++;
q.offer(temp.right);
}
}
thislevel = nextlevel;
nextlevel = 0;
}
}
}