设为首页 加入收藏

TOP

求二叉树的镜像,递归和非递归方式
2015-02-02 14:15:26 来源: 作者: 【 】 浏览:6
Tags:方式

1、二叉树定义:


typedef struct BTreeNodeElement_t_ {
? ? void *data;
} BTreeNodeElement_t;



typedef struct BTreeNode_t_ {
? ? BTreeNodeElement_t? ? *m_pElemt;
? ? struct BTreeNode_t_? ? *m_pLeft;
? ? struct BTreeNode_t_? ? *m_pRight;
} BTreeNode_t;


2、求二叉树镜像


例如:


? ? ? ? ? ? ? ? ? A? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? A


? ? ? ? B? ? ? ? ? ? ? ? C? ? ? ? ? ? ? ? ? ? ====>? ? ? ? ? ? ? ? ? ? C? ? ? ? ? ? B



? ? D? ? E? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? E? ? ? D?



(1)递归方式


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


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


void? BTreeMirror( BTreeNode_t *pRoot){
? ? if( pRoot == NULL )
? ? ? ? return ;


? ? BTreeNode_t *pTemp = pRoot->m_pLeft;
? ? pRoot->m_pLeft = pRoot->m_pRight;
? ? pRoot->m_pLeft = pTemp;


? ? BTreeMirror( pRoot->m_pLeft);
? ? BTreeMirror( pRoot->m_pRight);
? ? return;
}


(2)非递归方式


步骤描述:借助队列


首先,将根节点pRoot入队;


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


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


void? BTreeMirror( BTreeNode_t *pRoot){
? ? if( pRoot == NULL )
? ? ? ? return NULL;


? ? queue que;
? ? que.push(pRoot);
? ? int curLevelNodesTotal = 0;
? ? while( !que.empty()){
? ? ? ? curLevelNodesTotal = que.size();
? ? ? ? int cnt = 0;
? ? ? ? while( cnt < curLevelNodesTotal ){
? ? ? ? ? ? ++cnt;
? ? ? ? ? ? pRoot = que.front();
? ? ? ? ? ? que.pop();
? ? ? ? ? ? BTreeNode_t *pTemp = pRoot->m_pLeft:
? ? ? ? ? ? pRoot->m_pLeft = pRoot->m_pRight;
? ? ? ? ? ? pRoot->m_pRight = pTemp;


? ? ? ? ? ? if( pRoot->m_pLeft != NULL)
? ? ? ? ? ? ? ? que.push( pRoot->m_pLeft);
? ? ? ? ? ? if( pRoot->m_pRight != NULL )
? ? ? ? ? ? ? ? que.push( pRoot->m_pRight);
? ? ? ? }
? ? }


? ? return;
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇比较两个二叉树是否相同(结构和.. 下一篇求二叉树中任意两个节点之间的距..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: