Invert a binary tree.
Example:
Input:
4 / \ 2 7 / \ / \ 1 3 6 9Output:
4 / \ 7 2 / \ / \ 9 6 3 1
Trivia:
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 f*** off.
翻转二叉树。也是一道不会做,会写homebrew也枉然的题。题干即是题意。例子如下,即层层遍历,把左右子树交换。
两种思路,分别是层序遍历(BFS)和深度遍历(DFS)。
DFS
时间O(n)
空间O(n)
JavaScript实现
1 /** 2 * @param {TreeNode} root 3 * @return {TreeNode} 4 */ 5 var invertTree = function(root) { 6 if (root === null) return root; 7 let left = invertTree(root.left); 8 let right = invertTree(root.right); 9 root.left = right; 10 root.right = left; 11 return root; 12 };
Java实现
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public TreeNode invertTree(TreeNode root) { 18 if (root == null) return root; 19 TreeNode left = invertTree(root.left); 20 TreeNode right = invertTree(root.right); 21 root.left = right; 22 root.right = left; 23 return root; 24 } 25 }
BFS
时间O(n)
空间O(n)
JavaScript实现
1 /** 2 * @param {TreeNode} root 3 * @return {TreeNode} 4 */ 5 var invertTree = function(root) { 6 if (!root) return root; 7 let queue = [root]; 8 while (queue.length) { 9 let current = queue.shift(); 10 if (current === null) continue; 11 swap(current); 12 queue.push(current.left); 13 queue.push(current.right); 14 } 15 return root; 16 }; 17 18 var swap = tree => { 19 let temp = tree.left; 20 tree.left = tree.right; 21 tree.right = temp; 22 return tree; 23 };
Java实现
1 class Solution { 2 public TreeNode invertTree(TreeNode root) { 3 // corner case 4 if (root == null) { 5 return root; 6 } 7 8 // normal case 9 Queue<TreeNode> queue = new LinkedList<>(); 10 queue.offer(root); 11 while (!queue.isEmpty()) { 12 TreeNode cur = queue.poll(); 13 TreeNode temp = cur.left; 14 cur.left = cur.right; 15 cur.right = temp; 16 if (cur.left != null) { 17 queue.offer(cur.left); 18 } 19 if (cur.right != null) { 20 queue.offer(cur.right); 21 } 22 } 23 return root; 24 } 25 }