码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Populating Next Right Pointers in Each Node II"

时间:2014-07-26 17:02:11      阅读:316      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   div   ar   leetcode   log   

Compared with I version, the tree could be incomplete. The only difference is that, we connect current node‘s child to next non-childrenless‘ node‘s first child.

Still, we need calculate from right to left:

class Solution {
public:
    void connect(TreeLinkNode *p) {
        if (!p) return;

        if (p->right)
        {
            p->right->next = NULL;
            if (p->next)
            {
                TreeLinkNode *pTmp = p->next;
                while (pTmp)
                {
                    if (pTmp->left || pTmp->right) break;
                    pTmp = pTmp->next;
                }
                if (pTmp)
                {
                    if (pTmp->left) p->right->next = pTmp->left;
                    else if (pTmp->right) p->right->next = pTmp->right;
                }
            }
        }

        if (p->left)
        {
            if (p->right)    p->left->next = p->right;
            else
            {
                TreeLinkNode *pTmp = p->next;
                while (pTmp)
                {
                    if (pTmp->left || pTmp->right) break;
                    pTmp = pTmp->next;
                }
                if (pTmp)
                {
                    if (pTmp->left) p->left->next = pTmp->left;
                    else if (pTmp->right) p->left->next = pTmp->right;
                }
            }
        }
        connect(p->right);
        connect(p->left);
    }
};

LeetCode "Populating Next Right Pointers in Each Node II",布布扣,bubuko.com

LeetCode "Populating Next Right Pointers in Each Node II"

标签:style   blog   color   io   div   ar   leetcode   log   

原文地址:http://www.cnblogs.com/tonix/p/3870129.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!