Invert a binary tree.
Example:
Input:
1 2 3 4 5
| 4 / \ 2 7 / \ / \ 1 3 6 9
|
Output:
1 2 3 4 5
| 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.
1 递归
这太简单了…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
class Solution { public TreeNode invertTree(TreeNode root) { if(root == null) return root; TreeNode tmp = root.left; root.left = root.right; root.right = tmp; invertTree(root.left); invertTree(root.right); return root; } }
|
2 队列
再放一个非递归用队列实现的吧. 其实楼主在刻意的练习二叉树的非递归算法, 怕面试的时候简单题不让用递归, 不会的话就gg了.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
class Solution { public TreeNode invertTree(TreeNode root) { if(root == null) return root; Queue<TreeNode> q = new ArrayDeque<>(); q.offer(root); while(!q.isEmpty()) { int size = q.size(); while(size != 0) { TreeNode tmp = q.poll(); TreeNode dummy = tmp.left; tmp.left = tmp.right; tmp.right = dummy; if(tmp.left != null) q.offer(tmp.left); if(tmp.right != null) q.offer(tmp.right); --size; } } return root; } }
|