剑指Offer(Java版)第二十三题:操作给定的二叉树,将其变换为源二叉树的镜像。

/*
操作给定的二叉树,将其变换为源二叉树的镜像。
*/
//思路:根据二叉树中序的特点,使用栈来实现或者使用递归来实现。将镜像反转的特点和二叉树中序遍历的程序结合起来就可以实现了。

import java.util.*;

public class Class23 {

static class TreeNode{
double val;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val){
this.val = val;
}
}
//使用栈
public void MirrorTree(TreeNode tree){
if(tree == null){
return;
}
//创建一个栈
Stack<TreeNode> stack = new Stack<>();
while((tree != null) && (!stack.isEmpty())){
while(tree != null){
TreeNode tempNode = tree.left;
tree.left = tree.right;
tree.right = tempNode;
stack.push(tree);
tree = tree.left;
}
if(!stack.isEmpty()){
stack.pop();
tree = tree.right;
}
}
}
//使用递归
public void MirrorTree2(TreeNode tree){
if(tree == null){
return;
}
while(tree != null){
TreeNode tempNode = tree.left;
tree.left = tree.right;
tree.right = tempNode;
MirrorTree2(tree.left);
MirrorTree2(tree.right);
}

}

public static void main(String[] args) {
// TODO Auto-generated method stub

}

}

posted on 2020-03-11 21:43  桌子哥  阅读(183)  评论(0编辑  收藏  举报