题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。

https://www.nowcoder.com/practice/564f4c26aa584921bc75623e48ca3011

解题想法

递归思路:交换其左右子树,然后递归调用,交换子树。

非递归思路:涉及到反转,就应该想到栈,使用栈进行反转交换

代码实现

  • 递归版本
  1. /**
  2. public class TreeNode {
  3. int val = 0;
  4. TreeNode left = null;
  5. TreeNode right = null;
  6. public TreeNode(int val) {
  7. this.val = val;
  8. }
  9. }
  10. */
  11. public class Solution {
  12. public void Mirror(TreeNode root) {
  13. if (root == null){
  14. return;
  15. }
  16. TreeNode temp = root.left;
  17. root.left = root.right;
  18. root.right = temp;
  19. Mirror(root.left);
  20. Mirror(root.right);
  21. }
  22. }
  • 使用栈
  1. import java.util.Stack;
  2. /**
  3. public class TreeNode {
  4. int val = 0;
  5. TreeNode left = null;
  6. TreeNode right = null;
  7. public TreeNode(int val) {
  8. this.val = val;
  9. }
  10. }
  11. */
  12. public class Solution {
  13. public void Mirror(TreeNode root) {
  14. if(root == null){
  15. return;
  16. }
  17. Stack<TreeNode> stack = new Stack<TreeNode>();
  18. stack.push(root);
  19. while(!stack.isEmpty()){
  20. TreeNode rootTemp = stack.pop();
  21. TreeNode temp1 = rootTemp.left;
  22. rootTemp.left = rootTemp.right;
  23. rootTemp.right = temp1;
  24. if (rootTemp.left != null){
  25. stack.push(rootTemp.left);
  26. }
  27. if (rootTemp.right != null){
  28. stack.push(rootTemp.right);
  29. }
  30. }
  31. }
  32. }