# 剑指offer解题报告(Java版)——二叉树的镜像 19

public BinaryTreeNode mirrorRecursively(BinaryTreeNode root) {

if (root == null || (root.leftNode == null && root.rightNode == null))

return root;

// 交换左右子树

BinaryTreeNode tempBinaryTreeNode = root.leftNode;

root.leftNode = root.rightNode;

root.rightNode = tempBinaryTreeNode;

// 递归下去

if (root.leftNode != null) {

mirrorRecursively(root.leftNode);

}

if (root.rightNode != null) {

mirrorRecursively(root.rightNode);

}

return root;

}

public BinaryTreeNode mirrorStack(BinaryTreeNode root)

{

if(root==null)

return null;

BinaryTreeNode node=root;

Stack<BinaryTreeNode> stack=new Stack<BinaryTreeNode>();

while(node!=null || !stack.isEmpty())

{

while(node!=null)

{

BinaryTreeNode temp=node.leftNode;

node.leftNode=node.rightNode;

node.rightNode=temp;

stack.push(node);

node=node.leftNode;

}

node=stack.pop();

node=node.rightNode;

}

return root;

}

BinaryTreeNode root1=new BinaryTreeNode();

BinaryTreeNode node1=new BinaryTreeNode();

BinaryTreeNode node2=new BinaryTreeNode();

BinaryTreeNode node3=new BinaryTreeNode();

BinaryTreeNode node4=new BinaryTreeNode();

BinaryTreeNode node5=new BinaryTreeNode();

BinaryTreeNode node6=new BinaryTreeNode();

root1.leftNode=node1;

root1.rightNode=node2;

node1.leftNode=node3;

node1.rightNode=node4;

node2.leftNode=node5;

node2.rightNode=node6;

root1.data=8;

node1.data=6;

node2.data=10;

node3.data=5;

node4.data=7;

node5.data=9;

node6.data=11;

BinaryTreeNode root2=new BinaryTreeNode();

BinaryTreeNode a=new BinaryTreeNode();

BinaryTreeNode b=new BinaryTreeNode();

root2.leftNode=a;

root2.rightNode=b;

root2.data=8;

a.data=7;

b.data=2;

MirrorRecursively test=new MirrorRecursively();

BinaryTreeNode rootBinaryTreeNode=test.mirrorRecursively(root1);

System.out.println(root1.rightNode.leftNode.data);

原文作者：keedor
原文地址: https://www.cnblogs.com/keedor/p/4467590.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。