My recursive solution is easy and clean!


  • 25
    P
    void flatten(TreeNode* root) {
        if (!root) return;
        flatten(root->left);
        flatten(root->right);
        TreeNode *tmp = root->right;
        root->right = root->left;
        root->left = nullptr;
        while (root->right)
            root = root->right;
        root->right = tmp;
    }

  • 3
    M

    but need a lot of traversal in the "while" loop.. I prefer to return the end node of left part directly.


  • 0
    Y

    exactly, in the above code, you transversed down to flat the left tree, append the left tree to the right, then AGAIN traveled down the "left tree".


Log in to reply
 

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