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
        }
    };
  • 相关阅读:
    huffman编码
    查询选修了全部课程的学生姓名【转】
    java中的内部类
    jdbc技术
    多态
    存储过程,触发器,Mysql权限,备份还原
    sql查询重点
    常用的sql基础
    手动+工具开发动态资源
    Tomcat
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3889542.html
Copyright © 2011-2022 走看看