zoukankan      html  css  js  c++  java
  • 求二叉树镜像的递归非递归实现

    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. }  
  • 相关阅读:
    CF919F A Game With Numbers
    CF1005F Berland and the Shortest Paths
    CF915F Imbalance Value of a Tree
    CF1027F Session in BSU
    CF1029E Tree with Small Distances
    CF1037E Trips
    CF508E Arthur and Brackets
    CF1042F Leaf Sets
    [HNOI2012]永无乡
    [BZOJ1688][Usaco2005 Open]Disease Manangement 疾病管理
  • 原文地址:https://www.cnblogs.com/xiaodi914/p/5798492.html
Copyright © 2011-2022 走看看