Invert Binary Tree
Invert a binary tree.
4 / 2 7 / / 1 3 6 9to
4 / 7 2 / / 9 6 3 1Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
https://leetcode.com/problems/invert-binary-tree/
做出优秀的产品不代表代码优秀,反之亦然。
1 /** 2 * Definition for a binary tree node. 3 * function TreeNode(val) { 4 * this.val = val; 5 * this.left = this.right = null; 6 * } 7 */ 8 /** 9 * @param {TreeNode} root 10 * @return {TreeNode} 11 */ 12 var invertTree = function(root) { 13 swap(root); 14 return root; 15 16 function swap(node){ 17 if(node !== null){ 18 var tmp = node.left; 19 node.left = node.right; 20 node.right = tmp; 21 swap(node.left); 22 swap(node.right); 23 } 24 } 25 };