8ms c++ in place without recursion


  • 1
    N
    class Solution {
    public:
        void flatten(TreeNode* root) {
            if(!root) return;
            TreeNode* curr = root;
            TreeNode* pre = NULL;
            while(curr){
                if(!curr->left) curr = curr->right;
                else{
                    pre = curr->left;
                    while(pre->right) pre = pre->right;
                    if(!pre->right){
                        pre->right = curr->right;
                        curr->right = curr->left;
                        curr->left = NULL;
                        curr = curr->right;
                    }
                }
            }
        }
    };
    

  • 0
    V

    Impressive solution. The real in-place algorithm.


Log in to reply
 

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