方法一: 递归
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root!=null){
TreeNode tmp=root.left;
root.left=root.right;
root.right=tmp;
mirrorTree(root.left);
mirrorTree(root.right);
}
return root;
}
}
方法二:Stack
Stack的用法, stack.push(xxx)
stack.isEmpty()
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root==null) return null;
Stack<TreeNode> stack=new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node=stack.pop();
if(node.left!=null) stack.push(node.left);
if(node.right!=null) stack.push(node.right);
TreeNode tmp=node.left;
node.left=node.right;
node.right=tmp;
}
return root;
}
}