2014年5月8日星期四

Binary Tree Loop Solution - Populating Next Right Pointers in Each Node II

Both solutions work, and commented part is another data structure which is a LinkedList. Actually they are the same since Java implements Queue using LinkedList.

/**
 * 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;
//         }
//         TreeLinkNode pre = null;
//         TreeLinkNode levelHead = new TreeLinkNode(Integer.MIN_VALUE);
//         while(pre != null || levelHead.next == null){
//             TreeLinkNode cur = new TreeLinkNode(Integer.MIN_VALUE);
//             levelHead.next = cur;
//             if(pre == null){
//                 cur.next = root;
//                 cur = cur.next;
//                 cur.next = null;
               
//             }else{
//                 while(pre != null){
//                     if(pre.left != null){
//                         cur.next = pre.left;
//                         cur = cur.next;
//                     }
//                     if(pre.right != null){
//                         cur.next = pre.right;
//                         cur = cur.next;
//                     }
//                     pre = pre.next;
//                 }
//                 cur.next =  null;
//             }
//             pre = levelHead.next.next;
//         }
//     }
// }
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();
            }
        }
    }
}

没有评论: