【题目20】层序遍历一个棵二叉树
2009-09-19 15:34
423 查看
题目:怎样从顶部开始逐层打印二叉树结点数据?请编程。
分析:可以利用队列的先进先出的特性,逐次打印队列中的节点。
45
21 65
10 24 50 70
层序遍历的结果: 45,21,65,10,24,50,70
首先45入队,这时队列中有节点元素了,就取出一个来打印,并将
该节点的左子树和右子树分别入队(如果子树不为空的情况下),然后
取下一个先入队的元素打印,并将其左子树和右子树节点入队,一直这
样操作,直到队列为空,打印结束。
源代码:
分析:可以利用队列的先进先出的特性,逐次打印队列中的节点。
45
21 65
10 24 50 70
层序遍历的结果: 45,21,65,10,24,50,70
首先45入队,这时队列中有节点元素了,就取出一个来打印,并将
该节点的左子树和右子树分别入队(如果子树不为空的情况下),然后
取下一个先入队的元素打印,并将其左子树和右子树节点入队,一直这
样操作,直到队列为空,打印结束。
源代码:
#include <stdio.h> #include <stdlib.h> #define QSIZE 100 typedef struct BTree { int value; struct BTree* lChild; struct BTree* rChild; } BTree; //using the feature of the queue,first in first out struct MyQueue { BTree* queue[QSIZE]; int front; int rear; } myQueue; void InitQueue() { myQueue.rear = QSIZE - 1; myQueue.front = myQueue.rear; for(int i = 0;i < QSIZE;i++) myQueue.queue[i] = NULL; } int EnQueue(BTree* newNode) { if(myQueue.front >= 1) myQueue.queue[myQueue.front--] = newNode; else return 0; return 1; } BTree* DeQueue() { int t; if(myQueue.front != myQueue.rear){ t = myQueue.rear; myQueue.rear--; return myQueue.queue[t]; } else return NULL; } void LevelTraversal(BTree** root) { InitQueue(); BTree* lc = (BTree* ) malloc(sizeof(BTree)); BTree* rc = (BTree* ) malloc(sizeof(BTree)); BTree* p = (BTree* ) malloc(sizeof(BTree)); if((!lc) || (!rc) || (!p)){ printf("Out of memery/n"); exit(-1); } p = *root; if(!p) { printf("Empty Tree,build it first!/n"); } EnQueue(p); // enqueue the root of the tree while (myQueue.front != myQueue.rear){ p = DeQueue(); printf("%d ",p->value); lc = p->lChild; rc = p->rChild; if(lc != NULL) EnQueue(lc); if(rc != NULL) EnQueue(rc); } printf("/n"); } //recursively insert a tree node BTree* Insert(BTree* T, int value) { if(T == NULL) { T = (BTree*)malloc(sizeof(struct BTree)); if( T == NULL) printf("Malloc Failed."); else { T->value = value; T->lChild = T->rChild = NULL; } } else if(value < T->value) T->lChild = Insert(T->lChild,value); else if(value > T->value) T->rChild = Insert(T->rChild, value); return T; } BTree* MakeEmpty(BTree* T) { if(T != NULL) { MakeEmpty(T->lChild); MakeEmpty(T->rChild); free(T); } return NULL; } int main() { BTree* T = NULL; T = Insert(T,45); T = Insert(T,21); T = Insert(T,65); T = Insert(T,10); T = Insert(T,50); T = Insert(T,70); T = Insert(T,24); LevelTraversal(&T); MakeEmpty(T); return 0; }
相关文章推荐
- 算法与数据结构面试题(20)-层序遍历二叉树
- 算法题目-二叉树的层序遍历
- 二叉树创建及其遍历:前序、中序、后序、层序遍历等
- Binary Tree Level Order Traversal 二叉树的层序遍历
- python剑指offer系列层序遍历二叉树
- 实现二叉树的层序遍历,说说Java中的队列结构(实现一个Java的队列)
- 3344-层序遍历二叉树
- 层序遍历二叉树
- Java实现二叉树的前序、中序、后序、层序遍历(递归方法)
- 层序遍历二叉树
- 二叉树的遍历(先、中、后、层序)C实现
- 一种二叉树层序遍历实现
- 数据结构-二叉树基础题目小结(遍历,求节点数目等等)
- 二叉树层序遍历
- 二叉树---实现先序、中序、后序和层序遍历
- 二叉树的层序遍历
- 004-107-Binary Tree Level Order Traversal II 层序遍历二叉树之二
- 层序遍历二叉树(队列的使用)
- Binary Tree Level Order Traversal 二叉树的层序遍历
- 树——从最下层向上打印二叉树(层序遍历扩展)