C++算法之二叉树广度遍历
发布时间:2020-12-16 07:44:56 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 在二叉树的遍历当中,有一种遍历方法是不常见的,那就是广度遍历。和其他三种遍历方法不同,二叉树的广度遍历需要额外的数据结构来帮助一下?什么数据
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考
在二叉树的遍历当中,有一种遍历方法是不常见的,那就是广度遍历。和其他三种遍历方法不同,二叉树的广度遍历需要额外的数据结构来帮助一下?什么数据结构 呢?那就是队列。因为队列具有先进先出的特点,这个特点要求我们在遍历新的一层数据之前,必须对上一次的数据全部遍历结束。 ????a)下面是新添加的队列数据结构,其中数据部分换成了树节点指针的指针:
typedef struct _QUEUE { int head; int tail; int length; TREE_NODE** pHead; }QUEUE;????注:head表示开始,tail表示结束,length表示pHead的长度,pHead表示指针的起始地址 ????b)创建队列,因为涉及到length的长度问题,所以需要计算二叉树中节点的总数 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,sizeof(QUEUE)); pQueue->pHead = (TREE_NODE**)malloc(sizeof(TREE_NODE*)* count); assert(NULL != pQueue->pHead); memset(pQueue->pHead,sizeof(TREE_NODE*) * count); pQueue->head = pQueue->tail = 0; pQueue->length = count; return pQueue; }????c)实现队列的数据加入和数据弹出操作 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中得到的指针数据就是按层输出的结果 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进行赋值即可。不知道朋友们明白了没? 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |