一、题目内容

image.png

二、题解

解法1:

思路

时间(n),空间(1)

代码

  1. public class Solution {
  2. public TreeNode Mirror (TreeNode pRoot) {
  3. // write code here
  4. recur(pRoot);
  5. return pRoot;
  6. }
  7. private void recur(TreeNode root){
  8. if(root == null){
  9. return;
  10. }
  11. TreeNode temp = root.left;
  12. root.left = root.right;
  13. root.right = temp;
  14. recur(root.left);
  15. recur(root.right);
  16. }
  17. }

解法2:

思路

使用栈,时间(n),空间(n)

代码

  1. public class Solution {
  2. public TreeNode Mirror (TreeNode pRoot) {
  3. // write code here
  4. if(pRoot == null){
  5. return null;
  6. }
  7. Stack<TreeNode> stack = new Stack<>();
  8. stack.add(pRoot);
  9. while(!stack.isEmpty()){
  10. TreeNode node = stack.pop();
  11. if(node.left!=null){
  12. stack.add(node.left);
  13. }
  14. if(node.right!=null){
  15. stack.add(node.right);
  16. }
  17. TreeNode temp = node.left;
  18. node.left = node.right;
  19. node.right = temp;
  20. }
  21. return pRoot;
  22. }
  23. private void recur(TreeNode root){
  24. if(root == null){
  25. return;
  26. }
  27. TreeNode temp = root.left;
  28. root.left = root.right;
  29. root.right = temp;
  30. recur(root.left);
  31. recur(root.right);
  32. }
  33. }