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
    
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            if(root==NULL)
                return;
            
            root->next = NULL;
            fun(root);
        }
    private:
        TreeLinkNode *FindPleft(TreeLinkNode *&parent){
            TreeLinkNode *pleft =NULL;
            while(parent!=NULL){
                if(parent->left!=NULL){
                    pleft = parent->left;
                    break;
                }else if(parent->left==NULL && parent->right!=NULL){
                   pleft = parent->right;
                   break;
                }else{
                   parent = parent->next;
                   continue;
                }
            }//end while
            return pleft;
        }
        void fun(TreeLinkNode *parent){
            if(parent==NULL)
                return ;
            TreeLinkNode *pleft = FindPleft(parent);
            TreeLinkNode *pl;
            TreeLinkNode *nextLevelParent = pleft;
            while(parent!=NULL){
              if(pleft==parent->left &&parent->right!=NULL){
               pleft->next = parent->right;
               pleft = pleft->next;
            
              }else if((pleft!=NULL && pleft==parent->left && parent->right==NULL)||pleft==parent->right){
                  parent = parent->next;
                  if(parent==NULL||FindPleft(parent)==NULL){
                      pleft->next = NULL;
                      parent = nextLevelParent;
                      pl = FindPleft(parent);
                      pleft = pl;
                      nextLevelParent = pleft;
                  }else{
                      pl = FindPleft(parent);
                      pleft->next = pl;
                      pleft = pl;
                  }
              }//end if
                     
            }//end while
        }
    };
  • 相关阅读:
    java 导入导出的 命令
    点击 table 单元格 取值
    SQL Server存储过程创建和修改
    js正则匹配过滤 特殊字符
    java 学习框架
    Table 表单样式
    Table 表单
    Table 固定表头的几种方法
    .Net 高效开发之不可错过的实用工具
    sql 批量插入数据到Sqlserver中 效率较高的方法
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3889542.html
Copyright © 2011-2022 走看看