[Algorithm] 226. Invert Binary Tree

Invert a binary tree.

Example:

Input:

     4
   /   
  2     7
 /    / 
1   3 6   9

Output:

     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}
 */

// Using BFS to go though all the node
// if node has children, swap the children
var invertTree = function(root) {
   let stack = [root];
    
    while (stack.length !== 0) {
        let crt = stack.shift()
        
        if (crt != undefined) {
            var temp = crt.right;
            crt.right = crt.left
            crt.left = temp;

            stack.push(crt.left);        
            stack.push(crt.right);
        }
    }
    
    return root
};
原文地址:https://www.cnblogs.com/Answer1215/p/12292648.html