• 求二叉树镜像的递归非递归实现


    1、二叉树定义:

    [cpp] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. typedef struct BTreeNodeElement_t_ {  
    2.     void *data;  
    3. } BTreeNodeElement_t;  
    4.   
    5.   
    6. typedef struct BTreeNode_t_ {  
    7.     BTreeNodeElement_t     *m_pElemt;  
    8.     struct BTreeNode_t_    *m_pLeft;  
    9.     struct BTreeNode_t_    *m_pRight;  
    10. } BTreeNode_t;  



    2、求二叉树镜像

    例如:

                       A                                                                    A

            B                C                    ====>                    C             B

        D     E                                                                             E       D

    (1)递归方式

    如果pRoot为NULL,则为空树,返回;

    如果pRoot不为NULL,交换pRoot左右结点,然后分别求左右子树的镜像;

    [cpp] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. void  BTreeMirror( BTreeNode_t *pRoot){  
    2.     if( pRoot == NULL )  
    3.         return ;  
    4.   
    5.     BTreeNode_t *pTemp = pRoot->m_pLeft;  
    6.     pRoot->m_pLeft = pRoot->m_pRight;  
    7.     pRoot->m_pLeft = pTemp;  
    8.   
    9.     BTreeMirror( pRoot->m_pLeft);  
    10.     BTreeMirror( pRoot->m_pRight);  
    11.     return;  
    12. }  



    (2)非递归方式

    步骤描述:借助队列

    首先,将根节点pRoot入队;

    第一步:当队列未空时,获取当前层次的节点总数,即当前队列的长度;执行第二步;

    第二步:按照当前层的节点总数,出队进行遍历节点,在遍历时,交换左右节点,如果左右节点存在,则入队;当遍历完当前层所有节点时,遍历下一层,执行第一步。

    [cpp] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
      1. void   BTreeMirror( BTreeNode_t *pRoot){  
      2.     if( pRoot == NULL )  
      3.         return NULL;  
      4.   
      5.     queue <BTreeNode_t *> que;  
      6.     que.push(pRoot);  
      7.     int curLevelNodesTotal = 0;  
      8.     while( !que.empty()){  
      9.         curLevelNodesTotal = que.size();  
      10.         int cnt = 0;  
      11.         while( cnt < curLevelNodesTotal ){  
      12.             ++cnt;  
      13.             pRoot = que.front();  
      14.             que.pop();  
      15.             BTreeNode_t *pTemp = pRoot->m_pLeft:  
      16.             pRoot->m_pLeft = pRoot->m_pRight;  
      17.             pRoot->m_pRight = pTemp;  
      18.   
      19.             if( pRoot->m_pLeft != NULL)  
      20.                 que.push( pRoot->m_pLeft);  
      21.             if( pRoot->m_pRight != NULL )  
      22.                 que.push( pRoot->m_pRight);  
      23.         }  
      24.     }  
      25.   
      26.     return;  
      27. }  
  • 相关阅读:
    Mysql优化之6年工作经验总结
    mysql_innodb存储引擎的优化
    十六、MySQL授权命令grant的使用方法
    十五、Mysql字符集的那些事
    十四、索引
    十三、视图
    十二、存储过程
    十一、触发器
    十、存储引擎
    九、备份与恢复
  • 原文地址:https://www.cnblogs.com/xiaodi914/p/5798492.html
Copyright © 2020-2023  润新知