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);
    
                }
            }
    };
  • 相关阅读:
    What's the most secure desktop operating system?
    合肥一中在校学生丁雯琪(中美班)被麻省理工学院(MIT)录取
    Classic Computer Science 1980s-1990s
    HOWTO do Linux kernel development
    选择器zuoye
    HTML+css 小组件
    弹性盒子
    CSS3 学习笔记(动画 多媒体查询)
    CSS3 学习笔记(边框 背景 字体 图片 旋转等)
    学习笔记css3
  • 原文地址:https://www.cnblogs.com/diegodu/p/4415177.html
Copyright © 2011-2022 走看看