您的位置:首页 > 其它

一步一步写算法(之二叉树广度遍历)

2014-04-11 19:18 253 查看
原贴地址: http://blog.csdn.net/feixiaoxing/article/details/6897095

【 声明:版权所有,欢迎转载,请勿用于商业用途。  联系信箱:feixiaoxing @163.com】

    在二叉树的遍历当中,有一种遍历方法是不常见的,那就是广度遍历。和其他三种遍历方法不同,二叉树的广度遍历需要额外的数据结构来帮助一下?什么数据结构呢?那就是队列。因为队列具有先进先出的特点,这个特点要求我们在遍历新的一层数据之前,必须对上一次的数据全部遍历结束。暂时还没有掌握队列知识的朋友可以看一看我的这一篇博客—队列

    a)下面是新添加的队列数据结构,其中数据部分换成了树节点指针的指针:

[cpp] view
plaincopy

typedef struct _QUEUE  

{  

    int head;  

    int tail;  

    int length;  

    TREE_NODE** pHead;  

}QUEUE;  

    注:head表示开始,tail表示结束,length表示pHead的长度,pHead表示指针的起始地址

    b)创建队列,因为涉及到length的长度问题,所以需要计算二叉树中节点的总数

[cpp] view
plaincopy

QUEUE* create_queue_for_tree(const TREE_NODE* pTreeNode)  

{  

    QUEUE* pQueue;  

    int count;  

  

    if(NULL == pTreeNode)  

        return NULL;  

  

    count = count_all_node_number(pTreeNode);  

    pQueue = (QUEUE*)malloc(sizeof(QUEUE));  

    assert(NULL != pQueue);  

    memset(pQueue, 0, sizeof(QUEUE));  

  

    pQueue->pHead = (TREE_NODE**)malloc(sizeof(TREE_NODE*)* count);  

    assert(NULL != pQueue->pHead);  

    memset(pQueue->pHead, 0, sizeof(TREE_NODE*) * count);  

  

    pQueue->head = pQueue->tail = 0;  

    pQueue->length = count;  

    return pQueue;  

}  

    c)实现队列的数据加入和数据弹出操作

[cpp] view
plaincopy

void insert_node_into_queue(QUEUE* pQueue, TREE_NODE* pNode)  

{  

    if(NULL == pQueue || NULL == pQueue->pHead ||NULL == pNode)  

        return;  

  

    pQueue->pHead[pQueue->tail ++] = pNode;  

    return;  

}  

  

TREE_NODE* get_node_from_queue(QUEUE* pQueue)  

{  

    if(NULL == pQueue || NULL == pQueue->pHead)  

        return NULL;  

  

    if(pQueue->head == pQueue->tail)  

        return NULL;  

  

    return pQueue->pHead[pQueue->head++];  

}  

    注:这里定义的队列不是循环队列,所以数据的压入和弹出比较简单,直接对head和tail处理即可

    d)遍历节点,按层得到数据,最后再pQueue->pHead中得到的指针数据就是按层输出的结果

[cpp] view
plaincopy

QUEUE* traverse_node_by_layer(TREE_NODE* pNode)  

{  

    QUEUE* pQueue;  

    if(NULL ==pNode)  

        return NULL;  

  

    pQueue = create_queue_for_tree(pNode);  

    assert(NULL != pQueue);  

  

    /* 首个节点加入队列 */  

    insert_node_into_queue(pQueue, pNode);  

    pNode = get_node_from_queue(pQueue);  

  

    while(pNode){  

        if(pNode->left)  

            insert_node_into_queue(pQueue, pNode->left);  

  

        if(pNode->right)  

            insert_node_into_queue(pQueue, pNode->right);  

  

        pNode = get_node_from_queue(pQueue);  

    }  

  

    return pQueue;  

}  

扩充部分:

    上面的办法已经可以实现队列的按层输出,那么如果想在节点结构中直接实现数据的按层访问怎么办?其实两步走就可以:1)在已有的TREE_NODE添加prev和next;(2)按照刚才得到的pQueue->pHead结果,依次对prev和next进行赋值即可。不知道朋友们明白了没?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: