设为首页 加入收藏

TOP

按层遍历二叉树
2015-02-02 14:15:35 来源: 作者: 【 】 浏览:8
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、按层遍历二叉树


第一步:需要借助队列,首先将根节点pRoot入队;


第二步:当队列不空时,获得队首元素并出队,赋给pRoot,执行第三步;


第三步:如果pRoot左节点存在,则入队;如果pRoot右节点存在,则入队;执行第二步。


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


? ? queue ? 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 ;
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇求二叉树节点数,递归与非递归 下一篇求二叉树叶子节点个数,递归和非..

评论

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