JavaScript recursion - partial in-order solution


  • 0
    D
    
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {TreeNode}
     */
    var upsideDownBinaryTree = function(root) {
        
        if(!root){
            return [];
        }
        
        if(!root.left){
            return [root.val];
        }
        
        let newRoot = null;
        let newRootStart = null;
    
        let r = root;
        inorder(r);
    
        
        function inorder(r, prev){
    
    
            if(!r.left){
                newRoot = new TreeNode(r.val);
                newRootStart = newRoot;
                newRoot.left = prev.right;
                newRoot.right = new TreeNode(prev.val);
                newRoot = newRoot.right;
            }
    
            if(r.left){
                
                inorder(r.left, r);
    
                if(newRoot && prev){
                    //console.log(prev, r);
                    newRoot.left = prev.right;
                    newRoot.right = new TreeNode(prev.val);
                    newRoot = newRoot.right;
                }
    
            }
    
        }
    
        
        return newRootStart;
        
    };
    
    
    

Log in to reply
 

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