zoukankan      html  css  js  c++  java
  • [LeetCode] Populating Next Right Pointers in Each Node II

    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);
    
                }
            }
    };
  • 相关阅读:
    jQuery
    基于Js实现的UrlEncode和UrlDecode函数代码
    利用缓存、Timer间隔时间发送微信的实例,很有用的例子
    VisualStudio 自动排版等 快捷键
    正则表达式判断手机号码属于哪个运营商
    .Net常用方法汇总
    .NET中的三种Timer的区别和用法
    C# List和String互相转换
    Tempdb--TempDB Basic
    Tempdb--查看tempdb使用的脚本
  • 原文地址:https://www.cnblogs.com/diegodu/p/4415177.html
Copyright © 2011-2022 走看看