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

    Given a binary tree

        struct TreeLinkNode {
          TreeLinkNode *left;
          TreeLinkNode *right;
          TreeLinkNode *next;
        }
    

    Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

    Initially, all next pointers are set to NULL.

    Note:

    • You may only use constant extra space.
    • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

    For example,
    Given the following perfect binary tree,

             1
           /  
          2    3
         /   / 
        4  5  6  7
    

    After calling your function, the tree should look like:

             1 -> NULL
           /  
          2 -> 3 -> NULL
         /   / 
        4->5->6->7 -> NULL
    
    Hide Tags
     Tree Depth-first Search
    Have you met this question in a real interview? 
    Yes
     
    No
     

    Discuss

    这道题之所以放上来是因为题目中的那句话:You may only use constant extra space

    这就意味着,深搜是不能用的,因为递归是需要栈的,因此空间复杂度将是 O(logn)。毫无疑问广搜也不能用,因为队列也是占用空间的,空间占用还高于 O(logn)

    难就难在这里,深搜和广搜都不能用,怎么完成树的遍历?

    我拿到题目的第一反应便是:用广搜,接着发现广搜不能用,便犯了难。

    看了一些提示,有招了:核心仍然是广搜,但是我们可以借用 next 指针,做到不需要队列就能完成广度搜索。

    如果当前层所有结点的next 指针已经设置好了,那么据此,下一层所有结点的next指针 也可以依次被设置。

    class Solution {
        public:
            void connect(TreeLinkNode *root)
            {
                if(root == NULL)
                    return;
    
                TreeLinkNode* curLayer = root;//the leftmost node of the layer
    
                while(curLayer)
                {
                    TreeLinkNode* curNode = curLayer ;
                    while(curNode && curNode->left) //curNode is not a leaf node
                    {
                        TreeLinkNode* left = curNode->left;
                        TreeLinkNode* right= curNode->right;
    
                        left->next = right;
                        if(curNode->next)
                            right->next = curNode->next->left;
                        curNode = curNode->next;
                    }
                    curLayer = curLayer->left;
    
                }
            }
    };
  • 相关阅读:
    RESTful概念理解
    ORACLE数据库忘记SYS和SYSTEM密码,SYSTEM被锁定怎么办?
    MD5加密实现类不是Windows平台下联邦信息处理标准验证过的加密算法的一部分
    基于mqtt协议实现手机位置跟踪
    参考手册——掌握技术的重要途径
    在线编辑器跨域处理
    尝试新的东西
    BootStrap-DualListBox怎样改造成为双树
    软件开发中怎样有效地进行分析和设计
    引用数据被禁用时的解决办法
  • 原文地址:https://www.cnblogs.com/diegodu/p/4415009.html
Copyright © 2011-2022 走看看