*LeetCode-Populating Next Right Pointers in Each Node II

和第一题不一样的是不一定是complete tree

直接按level order traversal就好 就是用que 每次弄一行 add下一行

/**
 * 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;
        Queue<TreeLinkNode> que = new LinkedList<TreeLinkNode> ();
        que.add ( root );
        while ( !que.isEmpty() ){
            int size = que.size();
            for ( int i = 0; i < size; i ++ ){
                TreeLinkNode node = que.poll();
                if ( i == size - 1 )
                    node.next = null;
                else
                    node.next = que.peek();
                if ( node.left != null )
                    que.add( node.left);
                if ( node.right != null )
                    que.add ( node.right ); 
            }
        }
    }
}


你可能感兴趣的:(*LeetCode-Populating Next Right Pointers in Each Node II)