多叉树的深度遍历和广度遍历

多叉树的深度遍历和广度遍历,以三叉树为例,三叉树原型为

在这里插入图片描述


```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX 10

typedef struct Node{
	int d;
	struct Node *r_next;
	struct Node *m_next;
	struct Node *l_next;
}Node;

int pos=0;
int i=0;
int d[MAX]={0};
Node *s_head;

Node* getNewnode(int x){
	Node *node=(Node *)malloc(sizeof(Node));
	node->d=x;
	node->r_next=node->l_next=node->m_next=NULL;
	return node;
}

void DFS(Node *head){
	if(!head) return ;
	if(head==s_head){
		d[i]=head->d;
		i+=1;
	}
	if(head->l_next){
		d[i]=head->l_next->d;
		i+=1;
		DFS(head->l_next);
		printf("%02d ",d[i-1]);
		i-=1;
	}
	if(head->m_next){
		d[i]=head->m_next->d;
		i+=1;
		DFS(head->m_next);
		printf("%02d ",d[i-1]);
		i-=1;
	}
	if(head->r_next){
		d[i]=head->r_next->d;
		i+=1;
		DFS(head->r_next);
		printf("%02d ",d[i-1]);
		i-=1;
	}
	if(i==1) printf("%02d",d[i-1]);
	return ;
}

void BFS(Node *head){
	if(!head) return ;
	if(head==s_head){
		d[i]=head->d;
		i+=1;
	}
	if(head->l_next){
		d[i]=head->l_next->d;
		i+=1;
	}
	if(head->m_next){
		d[i]=head->m_next->d;
		i+=1;
	}
	if(head->r_next){
		d[i]=head->r_next->d;
		i+=1;
	}
	printf("%02d ",d[pos]);
	pos+=1;
	if(head->l_next) BFS(head->l_next);
	if(head->m_next) BFS(head->m_next);
	if(head->r_next) BFS(head->r_next);
	return ;
}

void clearNode(Node *head){
	if(head->r_next) clearNode(head->r_next);
	if(head->l_next) clearNode(head->l_next);
	if(head->m_next) clearNode(head->m_next);
	free(head);
	return ;
}

int main(void){
	srand(time(NULL));
	int k[MAX]={0};
	int j=1;
	for(;j<MAX;j++){
		k[j]=rand()%100;
		printf("%02d ",k[j]);
	}
	printf("\n");
	j=1;
	s_head=getNewnode(k[j]);
	j++;
	Node *temp=s_head;
	temp->l_next=getNewnode(k[j]);
	j++;
	temp->r_next=getNewnode(k[j]);
	j++;
	temp->l_next->l_next=getNewnode(k[j]);
	j++;
	temp=temp->r_next;
	temp->l_next=getNewnode(k[j]);
	j++;
	temp->m_next=getNewnode(k[j]);
	j++;
	temp->r_next=getNewnode(k[j]);
	j++;
	temp=temp->m_next;
	temp->l_next=getNewnode(k[j]);
	j++;
	temp->r_next=getNewnode(k[j]);
	BFS(s_head);
	printf("\n");
	i=0;
	DFS(s_head);
	clearNode(s_head);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值