首页 > 代码库 > [LeetCode] Populating Next Right Pointers in Each Node II

[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    }};