Invert Binary Tree (E)
Invert a binary tree.
Example:
Input:
4/ \2 7/ \ / \1 3 6 9
Output:
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.
题意
将二叉树的所有结点左右互换。
思路
简单的递归或者迭代。
代码实现 - 递归
class Solution {public TreeNode invertTree(TreeNode root) {if (root == null) {return null;}TreeNode left = invertTree(root.left);TreeNode right = invertTree(root.right);root.left = right;root.right = left;return root;}}
代码实现 - 迭代
class Solution {public TreeNode invertTree(TreeNode root) {if (root == null) {return null;}Queue<TreeNode> q = new ArrayDeque<>();q.offer(root);while (!q.isEmpty()) {TreeNode x = q.poll();TreeNode temp = x.left;x.left = x.right;x.right = temp;if (x.left != null) {q.offer(x.left);}if (x.right != null) {q.offer(x.right);}}return root;}}
