二叉树层次遍历算法

typedef struct BiTNode{
	ElemType data;
	struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

利用队列

#define MaxSize 30
typedef struct {
	ElemType data[MaxSize];
	int front, rear;
}SqQueue;

//初始化队列
void InitQueue(SqQueue &Q){
	Q.front = Q.rear = 0;
}

//判队列空
bool IsEmpty(SqQueue Q){
	if(Q.rear==Q.front)
		return true;
	else 
		return false;
}

//入队
bool EnQueue(SqQueue &Q, ElemType x){
	if((Q.rear+1)%MaxSize==Q.front) //队满
		return false;
	Q.data[Q.rear]=x;
	Q.rear=(Q.rear+1)%MaxSize;
	return true;
}

//出队
bool DeQueue(SqQueue &Q, ElemType &x){
	if(IsEmpty) return false;
	x=Q.data[Q.front];
	Q.front=(Q.front+1)%MaxSize;
	return true;
}

自上而下,从左到右遍历

void LevelOrder(BiTree T){
	InitQueue(Q);
	BiTree p;
	EnQueue(Q, T);  //先将根结点入队
	while(!IsEmpty(Q)){
		DeQueue(Q, p);
		visit(p);  //访问出队结点
		if(p->lchild!=NULL)
			EnQueue(Q, p->lchild);  //如果该出队结点左子树存在,则该左子树的根结点入队
		if(p->rchild!=NULL)
			EnQueue(Q, p->rchild);  //如果该出队结点右子树存在,则该右子树的根结点入队
	}
}

自下而上,从右到左遍历

其实就是将上面的层次遍历倒过来,可以将出队的元素依次入栈,然后再依次出栈。前一篇二叉树先中后序遍历算法里面已经写过栈,这里就不重复了

void LevelOrder2(BiTree T){
	InitQueue(Q);
	InitStack(S);
	BiTree p;
	EnQueue(Q, T);
	while(!IsEmpty(Q)){
		DeQueue(Q, p);
		Push(S, p);
		visit(p);
		if(p->lchild!=NULL)
			EnQueue(Q, p->lchild);
		if(p->rchild!=NULL)
			EnQueue(Q, p->rchild);
	}
	while(!IsEmpty(S)){
		Pop(S, p);
		visit(p);
	}
}
  • 0
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
二叉树层次遍历算法可以通过队列来实现。首先将根节点入队,然后进入循环,循环条件为队列不为空。在循环中,首先将队首节点出队并访问该节点,然后将该节点的左子节点和右子节点(如果有)依次入队。重复这个过程直到队列为空。这样就可以按层次顺序遍历二叉树了。 以下是二叉树层次遍历算法的C代码示例: ```c #include <stdio.h> #include <stdlib.h> // 二叉树节点的结构定义 typedef struct BTnode { char element; struct BTnode *left; struct BTnode *right; } BTnode; // 层次遍历函数 void levelOrderTraversal(BTnode *root) { if (root == NULL) { return; } // 创建一个队列,并将根节点入队 BTnode *queue[100]; int front = 0, rear = 0; queue[rear++] = root; while (front < rear) { // 出队并访问节点 BTnode *node = queue[front++]; printf("%c ", node->element); // 将左子节点和右子节点入队 if (node->left != NULL) { queue[rear++] = node->left; } if (node->right != NULL) { queue[rear++] = node->right; } } } int main() { // 创建一个二叉树(示例) BTnode *root = (BTnode*)malloc(sizeof(BTnode)); BTnode *node1 = (BTnode*)malloc(sizeof(BTnode)); BTnode *node2 = (BTnode*)malloc(sizeof(BTnode)); BTnode *node3 = (BTnode*)malloc(sizeof(BTnode)); BTnode *node4 = (BTnode*)malloc(sizeof(BTnode)); root->element = 'A'; node1->element = 'B'; node2->element = 'C'; node3->element = 'D'; node4->element = 'E'; root->left = node1; root->right = node2; node1->left = node3; node1->right = NULL; node2->left = NULL; node2->right = node4; node3->left = NULL; node3->right = NULL; node4->left = NULL; node4->right = NULL; // 层次遍历二叉树 levelOrderTraversal(root); return 0; } ``` 以上是二叉树层次遍历算法的C代码实现。你可以根据需要进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值