Pre-order solution


  • 4
    G

    use a pointer "pre", then pre order the tree.

    void flatten(TreeNode* root) {
        if (!root) return;
        TreeNode dummy(-1), *pre = &dummy;
        flatten(root, pre);
    }
    
    void flatten(TreeNode* root, TreeNode* &pre) {
        if (!root) return;
        TreeNode *rightChild = root->right;
        pre->right = root;
        pre->left = NULL;
        pre = root;
        flatten(root->left, pre);
        flatten(rightChild, pre);
    }

Log in to reply
 

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