Code Ganker: Populating Next Right Pointers in Each Node II -- LeetCode

2014年4月11日星期五

Populating Next Right Pointers in Each Node II -- LeetCode

原题链接: http://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
这道题目的要求和Populating Next Right Pointers in Each Node是一样的,只是这里的二叉树没要求是完全二叉树。其实在实现Populating Next Right Pointers in Each Node的时候我们已经兼容了不是完全二叉树的情况,其实也比较好实现,就是在判断队列结点时判断一下他的左右结点是否存在就可以了。具体算法就不再分析了,不熟悉的朋友可以看看Populating Next Right Pointers in Each Node。时间复杂度和空间复杂度不变,还是O(n)和O(1)。代码如下:
public void connect(TreeLinkNode root) {
    if(root == null)
        return;
    TreeLinkNode lastHead = root;
    TreeLinkNode pre = null;
    TreeLinkNode curHead = null;
    while(lastHead!=null)
    {
        TreeLinkNode lastCur = lastHead;
        while(lastCur != null)
        {
            if(lastCur.left!=null)
            {
                if(curHead == null)
                {
                    curHead = lastCur.left;
                    pre = curHead;
                }
                else
                {
                    pre.next = lastCur.left;
                    pre = pre.next;
                }
            }
            if(lastCur.right!=null)
            {
                if(curHead == null)
                {
                    curHead = lastCur.right;
                    pre = curHead;
                }
                else
                {
                    pre.next = lastCur.right;
                    pre = pre.next;
                }
            }                
            lastCur = lastCur.next;

        }
        lastHead = curHead;
        curHead = null;
    }
}
这道题本质是树的层序遍历,只是队列改成用结点自带的链表结点来维护。

3 条评论:

  1. Your solution to this problem is very inspiring to me. Thank you!

    回复删除
  2. This is my short Source code:

    public class Solution {
    public void connect(TreeLinkNode root) {

    while(root != null){
    TreeLinkNode tempChild = new TreeLinkNode(0);
    TreeLinkNode currentChild = tempChild;
    while(root!=null){
    if(root.left != null) { currentChild.next = root.left; currentChild = currentChild.next;}
    if(root.right != null) { currentChild.next = root.right; currentChild = currentChild.next;}
    root = root.next;
    }
    root = tempChild.next;
    }
    }
    }

    URL: http://traceformula.blogspot.com/2015/06/populating-next-right-pointers-in-each.html

    回复删除
  3. This is my short Source code:

    public class Solution {
    public void connect(TreeLinkNode root) {

    while(root != null){
    TreeLinkNode tempChild = new TreeLinkNode(0);
    TreeLinkNode currentChild = tempChild;
    while(root!=null){
    if(root.left != null) { currentChild.next = root.left; currentChild = currentChild.next;}
    if(root.right != null) { currentChild.next = root.right; currentChild = currentChild.next;}
    root = root.next;
    }
    root = tempChild.next;
    }
    }
    }

    URL: http://traceformula.blogspot.com/2015/06/populating-next-right-pointers-in-each.html

    回复删除