[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/xkDMW/JavaScript-Algorithms/master/leetcode/invert-binary-tree.js [Back]  [Original]

//
/**
 * Question:
 *  Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9

* to

     4
   /   \
  7     2
 / \   / \
9   6 3   1

 * 
 * /


/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function(root) {
    if (root){
        // 
        root.left = [invertTree(root.right), root.right = invertTree(root.left)][0];
    }
    return root;
};


// 
var invertTree = function(root) {
    if (root !== null) {
        var nodes = [root];
        while(nodes.length) {
            //node
            var node = nodes.shift();
            if(node === null) continue;
            
            //
            nodes.push(node.left);
            nodes.push(node.right);
            
            //
            node.right = [node.left, node.left = node.right][0];
    
        }
    }
    
    return root;
};

Web Proxy Viewer  |  New URL  |  Original Page