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 static void connect(TreeLinkNode root) {
if(root == null)
return;
TreeLinkNode dummy = new TreeLinkNode(-1); //新建一个节点,其next用于指向每一层的第一个节点
TreeLinkNode cur;
TreeLinkNode prev = dummy; //用于连接这一层的所有节点
for(cur=root; cur !=null; cur = cur.next){ //因为是至上到下的连接,所以依次向后直到遇到空节点
if(cur.left !=null)
{
prev.next = cur.left;
prev = prev.next;
}
if(cur.right !=null){
prev.next = cur.right;
prev = prev.next;
}
}
connect(dummy.next); //然后再以上一层的一个节点为根节点把下一层的节点连接