二叉樹(11)----求二叉樹的鏡像,遞歸和非遞歸方式
阿新 • • 發佈:2017-07-10
temp right 二叉樹 -a data nbsp rac art urn
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 <BTreeNode_t *> 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; }
二叉樹(11)----求二叉樹的鏡像,遞歸和非遞歸方式