多叉树的深度遍历和广度遍历,以三叉树为例,三叉树原型为
```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;
}