题目:给定一棵树,反转这棵树得到树的镜像
例如:
分析:通过画图可知,得到一棵树的镜像只需要将该树的左右子树调换位置即可
代码如下:
package problem2;
/**
* @author Hutongling
*/
public class 二叉树的镜像 {
static void binTreeMiorr(TreeNode root){
if(root==null)
return ;
TreeNode treeNode;
if(root!=null){
treeNode=root.leftChild;
root.leftChild=root.rightChild;
root.rightChild=treeNode;
binTreeMiorr(root.getLeftChild());
binTreeMiorr(root.getRightChild());
}
}
//先根遍历树(使用递归)
static void inOrder(TreeNode root){
if(root==null)
return;
if(root!=null){
System.out.print(root.getValue() + " ");
inOrder(root.getLeftChild());
inOrder(root.getRightChild());
}
}
public static void main(String[] args) {
TreeNode paremtRoot=new TreeNode(8);
TreeNode rootChild1=new TreeNode(8);
TreeNode rootChild2=new TreeNode(7);
TreeNode child1Child1=new TreeNode(9);
TreeNode child1Child2=new TreeNode(2);
TreeNode child12Child1=new TreeNode(4);
TreeNode child12Child2=new TreeNode(7);
paremtRoot.setLeftChild(rootChild1);
paremtRoot.setRightChild(rootChild2);
rootChild1.setLeftChild(child1Child1);
rootChild1.setRightChild(child1Child2);
child1Child2.setLeftChild(child12Child1);
child1Child2.setRightChild(child12Child2);
System.out.println("原树为(先根遍历):");
inOrder(paremtRoot);
System.out.println();
binTreeMiorr(paremtRoot);
System.out.println("镜像树为(先根遍历):");
inOrder(paremtRoot);
}
}
结果如下:
原树为(先根遍历):
8 8 9 2 4 7 7
镜像树为(先根遍历):
8 7 8 2 7 4 9