面试题19 二叉树的镜像

例如:下面两棵树互为镜像


思路:先序遍历树的每个结点,若遍历到的结点有子节点,则交换它的两个结点。

代码:

[cpp]  view plain copy
  1. #include "stdafx.h"  
  2. #include <iostream>  
  3. using namespace std;  
  4.   
  5. struct BinaryTreeNode  
  6. {  
  7.     int m_nValue;  
  8.     BinaryTreeNode *m_pLeft;  
  9.     BinaryTreeNode *m_pRight;  
  10. };  
  11.   
  12. //构造树的镜像  
  13. void Mirror(BinaryTreeNode *pRoot)  
  14. {  
  15.    if (pRoot != NULL)  
  16.    {  
  17.        BinaryTreeNode *pTemp = NULL;  
  18.        if (pRoot->m_pLeft != NULL || pRoot->m_pRight != NULL)  
  19.        {  
  20.            pTemp = pRoot->m_pLeft;  
  21.            pRoot->m_pLeft = pRoot->m_pRight;  
  22.            pRoot->m_pRight = pTemp;  
  23.        }  
  24.   
  25.        if (pRoot->m_pLeft != NULL)  
  26.        {  
  27.            Mirror(pRoot->m_pLeft);  
  28.        }  
  29.   
  30.        if (pRoot->m_pRight != NULL)  
  31.        {  
  32.            Mirror(pRoot->m_pRight);  
  33.        }  
  34.    }  
  35. }  
  36.   
  37. //以先序的方式构建二叉树,输入-1表示结点为空  
  38. void CreateBinaryTree(BinaryTreeNode *&pRoot)  
  39. {  
  40.     int nNodeValue = 0;  
  41.     cin >> nNodeValue;      
  42.     if (-1 == nNodeValue)  
  43.     {  
  44.         return;   
  45.     }  
  46.     else  
  47.     {  
  48.         pRoot = new BinaryTreeNode();  
  49.         pRoot->m_nValue = nNodeValue;  
  50.         CreateBinaryTree(pRoot->m_pLeft);  
  51.         CreateBinaryTree(pRoot->m_pRight);  
  52.     }  
  53. }  
  54.   
  55. void PrintInOrder(BinaryTreeNode *&pRoot)  
  56. {  
  57.     if (pRoot != NULL)  
  58.     {  
  59.         PrintInOrder(pRoot->m_pLeft);  
  60.         cout << pRoot->m_nValue << " ";  
  61.         PrintInOrder(pRoot->m_pRight);  
  62.     }  
  63. }  
  64.   
  65. int _tmain(int argc, _TCHAR* argv[])  
  66. {  
  67.     BinaryTreeNode *pRoot = NULL;  
  68.     CreateBinaryTree(pRoot);  
  69.     PrintInOrder(pRoot);  
  70.     cout << endl;  
  71.       
  72.     Mirror(pRoot);  
  73.     PrintInOrder(pRoot);  
  74.     cout << endl;  
  75.   
  76.     system("pause");  
  77.     return 0;  
  78. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值