Invert Binary Tree (E)

Invert a binary tree.

Example:

Input:

  1. 4
  2. / \
  3. 2 7
  4. / \ / \
  5. 1 3 6 9

Output:

  1. 4
  2. / \
  3. 7 2
  4. / \ / \
  5. 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. class Solution {
  2. public TreeNode invertTree(TreeNode root) {
  3. if (root == null) {
  4. return null;
  5. }
  6. TreeNode left = invertTree(root.left);
  7. TreeNode right = invertTree(root.right);
  8. root.left = right;
  9. root.right = left;
  10. return root;
  11. }
  12. }

代码实现 - 迭代

  1. class Solution {
  2. public TreeNode invertTree(TreeNode root) {
  3. if (root == null) {
  4. return null;
  5. }
  6. Queue<TreeNode> q = new ArrayDeque<>();
  7. q.offer(root);
  8. while (!q.isEmpty()) {
  9. TreeNode x = q.poll();
  10. TreeNode temp = x.left;
  11. x.left = x.right;
  12. x.right = temp;
  13. if (x.left != null) {
  14. q.offer(x.left);
  15. }
  16. if (x.right != null) {
  17. q.offer(x.right);
  18. }
  19. }
  20. return root;
  21. }
  22. }