二叉树(6)----按层遍历二叉树

来源:互联网 发布:阿里巴巴美工招聘 编辑:程序博客网 时间:2024/05/22 17:51

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


1 0
原创粉丝点击