2 similar-non-recursive-solution analysis


  • 0

    Having seen others' posts. I find the non-recursive-solution-ideas are all similar.

      set the cur-root-left-sub-tree to the intra-place-between cur-root and cur-root-right-sub-tree
    
      move  the cur-root  =  cur-root->right
    
    
       class Solution {
        public:
            /*** non-recursive-implementation method 1  ***/
            void flatten(TreeNode* root) {
                TreeNode* cur=root;
                while(cur){
                    if(cur->left){
                        TreeNode* pre=cur->left;
                        while(pre->right){
                            pre=pre->right;
                        }
                        pre->right=cur->right;
                        cur->right=cur->left;
                        cur->left=NULL;
                    }
                    cur=cur->right;
                }
            }
            
            /*** non-recursive-implementation method 2  ***/
            void flatten(TreeNode* root){
                while(root){
                    if(root->left && root->right){
                        TreeNode* temp=root->left;
                        while(temp->right)
                            temp=temp->right;
                        temp->right=root->right;
                    }
                    if(root->left)
                        root->right=root->left;
                    root->left=NULL;
                    root = root->right;
                }
            }
        };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.