6 line C++ solution


  • 0
    H

    From the given example, this transformation can be interpreted as a kind of post-order traversal. A post-order traversal is a recursive traversal of a tree where the children are explored first, followed by the current node.

    In this case, looking at the generated list, the right subtree is explored first. As we explore the nodes, we store the pointer to the last tree node visited, and set the right child of the current node to this pointer (last). The left child is always NULL.

    class Solution {
    private:
        TreeNode* last = nullptr;
    public:
        void flatten(TreeNode* root) {
            if (!root) return;
            flatten(root->right);
            flatten(root->left);
            root->left  = nullptr;
            root->right = last;
            last = root;
        }
    };
    

Log in to reply
 

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