• [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
        }
    };
  • 相关阅读:
    ZOJ 1060 Count the Color
    POJ 3321 Apple Tree
    数字三角形模型
    静态维护区间加等差数列的求和问题
    Codeforces Round #622 (Div. 2)-题解
    算法竞赛进阶指南0x00-算法基础
    Codeforces Round #628 (Div. 2)
    Codeforces Round #625 (Div. 2, based on Technocup 2020 Final Round)
    Codeforces Round #621 (Div. 1 + Div. 2)
    Codeforces Round #620 (Div. 2) 题解
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3889542.html
Copyright © 2020-2023  润新知