117. Populating Next Right Pointers in Each Node II

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

一刷
题解:
创建3个节点,cur(处于当前层), prev(处于操作层), head(下一层的最外节点)。即 cur-1, prev-2, head-3

/**
 * 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) {
        TreeLinkNode head = null;//the head of the next level
        TreeLinkNode prev = null;// the leading node of next level
        TreeLinkNode cur = root; //current node of current level
        
        //cur-1, prev-2, head-3
        
        while(cur!=null){
            while(cur!=null){
                //current manipulate-level 2
                if(cur.left!=null){
                    if(prev == null){
                        head = cur.left;
                    }
                    else prev.next = cur.left;
                    prev = cur.left;
                }
                
                if(cur.right!=null){
                    if(prev == null) head = cur.right;
                    else prev.next = cur.right;
                    prev = cur.right;
                }
                cur = cur.next;
            }
            cur = head;
            head = null;
            prev = null;
        }
    }
}

你可能感兴趣的:(117. Populating Next Right Pointers in Each Node II)