Invert a binary tree.
Example:
Input:
4 / 2 7 / / 1 3 6 9Output:
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 };