[leetcode]Populating Next Right Pointers in Each Node

这道题目如果不用常数级的空间是很容易的,就是用一个queue呗。

public class Solution {
    public void connect(TreeLinkNode root) {
        LinkedList<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
        queue.offer(root);
        int count = 0;
        int lastCount = 0;
        TreeLinkNode last = null;
        while (queue.size() != 0)
        {
            TreeLinkNode n = queue.poll();
            if (n == null) continue;
            count++;
            if (last != null) last.next = n;
            if (lastCount == 0 || count == lastCount * 2)
            {
                lastCount = count;
                count = 0;
                n.next = null;
                last = null;
            }
            else {
                last = n;
            }
            queue.offer(n.left);
            queue.offer(n.right);
        }
    }
}

但是题目要求常数级空间,怎么办呢?当时想啊,如果没有queue可怎么做到同一层从左到右遍历啊,后来搜索了之后发现其实可以用next指针嘛。其他还有递归法,精神就一样了。参见:http://blog.csdn.net/ithomer/article/details/8796542

public class Solution {
    public void connect(TreeLinkNode root) {
        TreeLinkNode left = root;
        TreeLinkNode n = null;
        while (left != null && left.left != null && left.right != null)
        {
            n = left;
            while (n != null)
            {
                n.left.next = n.right;
                if (n.next != null)
                {
                    n.right.next = n.next.left;
                }
                n = n.next;
            }
            left = left.left;
        }
    }
}

  

posted @ 2013-08-28 22:29  阿牧遥  阅读(199)  评论(0编辑  收藏  举报