10ms C++ solution


  • 1
    Y
    class Solution {
    public:
        void flatten(TreeNode* root) {
            if(root == NULL) return;
            dfs(root);
        }
        
        TreeNode* dfs(TreeNode* node) {
            TreeNode *lNode = NULL, *rNode = NULL, *lastNode;
            if(node->left != NULL) {
                lNode = dfs(node->left);
            }
            if(node->right != NULL) {
                rNode = dfs(node->right);
            }
            if(lNode != NULL) {
                lNode->right = node->right;
                node->right = node->left;
            }
            if(rNode != NULL) lastNode = rNode;
            else if(lNode != NULL) lastNode = lNode;
            else lastNode = node;
            node->left = NULL;
            return lastNode;
        }
    };

Log in to reply
 

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