2014年5月8日星期四

Binary Tree Queue Solution - Populating Next Right Pointers in Each Node

The idea is to load tree nodes by level into a queue. By checking the level size if 0 then next to be null, and reset the level size; otherwise the next points to the peek… until the queue is empty.


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

没有评论: