Javascript, recursion&iteration


  • 0
    Y



    var upsideDownBinaryTree = function(root) {
    if(!root) return null;
    return help(root);
    };

    
    function help(node) {
        if(!node.left) return node;
        var tmp = help(node.left);
        node.left.left = node.right;
        node.right = null;
        node.left.right = node;
        node.left = null;
        return tmp;
    }
    
    
    
    var upsideDownBinaryTree = function(root) {
        if(!root || !root.left) return root;
        var left = root.left;
        var right = root.right;
        var top = root;
        top.left = null;
        top.right = null;
        while(left) {
            var nextLeft = left.left;
            var nextRight = left.right;
            left.right = top;
            left.left = right;
            top = left;
            left = nextLeft;
            right = nextRight;
        }
        return top;
    };
    
    

Log in to reply
 

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