一、题目内容
二、题解
解法1:
思路
时间(n),空间(1)
代码
public class Solution { public TreeNode Mirror (TreeNode pRoot) { // write code here recur(pRoot); return pRoot; } private void recur(TreeNode root){ if(root == null){ return; } TreeNode temp = root.left; root.left = root.right; root.right = temp; recur(root.left); recur(root.right); }}
解法2:
思路
使用栈,时间(n),空间(n)
代码
public class Solution { public TreeNode Mirror (TreeNode pRoot) { // write code here if(pRoot == null){ return null; } Stack<TreeNode> stack = new Stack<>(); stack.add(pRoot); while(!stack.isEmpty()){ TreeNode node = stack.pop(); if(node.left!=null){ stack.add(node.left); } if(node.right!=null){ stack.add(node.right); } TreeNode temp = node.left; node.left = node.right; node.right = temp; } return pRoot; } private void recur(TreeNode root){ if(root == null){ return; } TreeNode temp = root.left; root.left = root.right; root.right = temp; recur(root.left); recur(root.right); }}