二叉樹(6)----按層遍歷二叉樹
阿新 • • 發佈:2018-12-24
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、按層遍歷二叉樹
第一步:需要藉助佇列,首先將根節點pRoot入隊;
第二步:當佇列不空時,獲得隊首元素並出隊,賦給pRoot,執行第三步;
第三步:如果pRoot左節點存在,則入隊;如果pRoot右節點存在,則入隊;執行第二步。
void LevelTraverse( BTreeNode_t *pRoot){ if( pRoot == NULL ) return ; queue <BTreeNode_t *> que; que.push( pRoot); while( !que.empty() ){ pRoot = que.front(); que.pop(); Visit( pRoot); if( pRoot->m_pLeft != NULL ) que.push( pRoot->m_pLeft ); if( pRoot->m_pRight != NULL ) que.push( pRoot->m_pRight); } return ; }