首页 > 其他 > 详细

[LeetCode] Populating Next Right Pointers in Each Node II

时间:2015-04-10 19:33:40      阅读:207      评论:0      收藏:0      [点我收藏+]

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

 

For example,
Given the following binary tree,

         1
       /        2    3
     / \        4   5    7

 

After calling your function, the tree should look like:

         1 -> NULL
       /        2 -> 3 -> NULL
     / \        4-> 5 -> 7 -> NULL

 

 

Hide Tags
 Tree Depth-first Search
 
思路:接Populating Next Right Pointers in Each Node 还是如果当前层所有结点的next 指针已经设置好了,那么据此,下一层所有结点的next指针 也可以依次被设置。
只是,如何找到下一层最左侧的节点,以及如何找到自己节点右边的节点的最左节点需要麻烦些,我自己写了个findLeftMostOfNextLayer
class Solution {
    public:
        TreeLinkNode* findLeftMostOfNextLayer(TreeLinkNode * root)
        {
            if(root == NULL)
                return NULL;
            if(root->left)
                return root->left;
            if(root->right)
                return root->right;
            return findLeftMostOfNextLayer(root->next);
        }


        void connect(TreeLinkNode *root)
        {
            if(root == NULL)
                return;

            TreeLinkNode* curLayer = root;//the leftmost node of the layer

            while(curLayer)
            {
                TreeLinkNode* curNode = curLayer ;
                while(curNode)
                {
                    TreeLinkNode* left = curNode->left;
                    TreeLinkNode* right= curNode->right;
                    TreeLinkNode* next = findLeftMostOfNextLayer(curNode->next);
                    //curNode is not a leaf node
                    if(left && right)
                    {
                        left->next = right;
                    }

                    if(next)
                    {
                        if(right)
                            right->next = next;
                        else if(left)
                            left->next = next;
                    }
                    curNode = curNode->next;
                }
                curLayer = findLeftMostOfNextLayer(curLayer);

            }
        }
};

 

[LeetCode] Populating Next Right Pointers in Each Node II

原文:http://www.cnblogs.com/diegodu/p/4415177.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!