C++ solution with DFS


  • 0
    X
    class Solution {
    public:
        TreeNode *p;
    
        void dfs(TreeNode *root, TreeNode *&p) {
            TreeNode *left = root->left;
            TreeNode *right = root->right;
            if (p == NULL) {
                p = root;
                p->left = p->right = NULL;
            } else {
                p->right = root;
                p = p->right;
                p->left = p->right = NULL;
            }
            if (left)
                dfs(left, p);
            if (right)
                dfs(right, p);
        }
        
        void flatten(TreeNode *root) {
            if (!root)
                return;
            p = NULL;
            dfs(root, p);
            return;
        }
    };
    

Log in to reply
 

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