面试题19二叉树的镜像

https://blog.csdn.net/u010425776/article/details/50886193

 

 

 分析:所谓“镜像”就是从镜子里看到的样子。我们可以画一棵二叉树,然后画出该二叉树的镜像。画完图之后我们会发现,所谓“二叉树的镜像”就是把二叉树中所有子树的左孩子和右孩子进行交换。因此需要遍历二叉树所有的结点,在遍历的同时交换非叶子结点的左右子树。遍历我们可以使用先序遍历,首先判断当前根结点是否为叶子结点,若非叶子结点,则交换左右孩子,然后再分别对左右孩子进行相同的操作。

   首先,我们需要构造二叉树的结点类,一个结点中包含一个数据域data、一个左孩子left、一个右孩子right,代码如下:

 

 
  1. /**

  2. * 二叉树的结点

  3. */

  4. class BinaryTreeNode<T>{

  5. T data;//结点的数据域

  6. BinaryTreeNode<T> left;//左子树

  7. BinaryTreeNode<T> right;//右子树

  8. }

 

 

 

 

 

下面开始编写镜像函数:

 

 
  1. /**

  2. * 二叉树镜像函数

  3. * @param root 输入二叉树的根结点

  4. */

  5. public static <T> void binaryTreeMirror(BinaryTreeNode<T> root){

  6. //若二叉树为空

  7. if(root==null)

  8. return;

  9.  
  10. //若二叉树只有一个结点

  11. if(root.left==null && root.right==null)

  12. return;

  13.  
  14. //若二叉树为有孩子结点,则交换左右子树

  15. {

  16. //交换左右子树

  17. BinaryTreeNode<T> temp = root.left;

  18. root.left = root.right;

  19. root.right = temp;

  20. }

  21.  
  22. //分别对左右重复上述操作

  23. {

  24. if(root.left!=null)

  25. binaryTreeMirror(root.left);

  26. if(root.right!=null)

  27. binaryTreeMirror(root.right);

  28. }

  29. }


为了能够对上述算法进行测试,我编写了一个二叉树的中序遍历函数,我们可以比较二叉树镜像前和镜像后的中序遍历结果来判断算法是否正确。二叉树中序遍历函数如下:

 

 

 
  1. <span style="white-space:pre"> </span>/**

  2. * 二叉树的中序遍历

  3. * @param root 输入的二叉树的根

  4. */

  5. public static <T> void preOrder(BinaryTreeNode<T> root){

  6. //若当前二叉树为空

  7. if(root==null)

  8. return;

  9.  
  10. //中序遍历二叉树

  11. {

  12. preOrder(root.left);//中序遍历左子树

  13. System.out.print(root.data+",");//访问根结点

  14. preOrder(root.right);//中序遍历右子树

  15. }

  16. }


一切准备工作就绪,下面就开始测试我们的算法吧。

 

我创建了一棵四个结点的二叉树,并且所有结点均是左孩子。那么经过镜像后该二叉树的所有结点应该都是右孩子。并且前后两棵树的中序遍历正好是逆序关系。

 

 
  1. public static void main(String[] args){

  2. BinaryTreeNode<Integer> root = new BinaryTreeNode<Integer>();

  3. BinaryTreeNode<Integer> root1 = new BinaryTreeNode<Integer>();

  4. BinaryTreeNode<Integer> root2 = new BinaryTreeNode<Integer>();

  5. BinaryTreeNode<Integer> root3 = new BinaryTreeNode<Integer>();

  6. root.data = 0;

  7. root1.data = 1;

  8. root2.data = 2;

  9. root3.data = 3;

  10. root.left = root1;

  11. root1.left = root2;

  12. root2.left = root3;

  13.  
  14. System.out.println("镜像前:");

  15. preOrder(root);

  16. System.out.println("镜像后:");

  17. binaryTreeMirror(root);

  18. preOrder(root);

  19.  
  20. }

 

 

 

输出结果为:

镜像前:3,2,1,0

镜像后:0,1,2,3

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值