#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<queue>
using namespace std;
typedef struct tree#二叉树的结构体
{
char data;
tree *left;
tree *right;
}tree;
tree *creattree()#二叉树的建立
{
tree *T;
char a=getchar();
if(a==' ')
a=getchar();
if(a=='*')
return NULL;
else
{
T=(tree *)malloc(sizeof(tree));
T->data=a;
T->left=creattree();
T->right=creattree();
return T;
}
}
void preorder(tree *T)#前序遍历
{
if(T)
{
printf("%c ",T->data);
preorder(T->left);
preorder(T->right);
}
}
void inorder(tree *T)#中序遍历
{
if(T)
{
inorder(T->left);
printf("%c ",T->data);
inorder(T->right);
}
}
void lastorder(tree *T)#后序遍历
{
if(T)
{
lastorder(T->left);
lastorder(T->right);
printf("%c ",T->data);
}
}
void dfs(tree *T)#层次遍历
{
queue<tree *> L;
L.push(T);
tree *s;
while(!L.empty())
{
s=L.front();
L.pop();
printf("%c ",s->data);
if(s->left)
{
L.push(s->left);
}
if(s->right)
{
L.push(s->right);
}
}
}
int main()
{
tree *T=creattree();
if(T==NULL)
return 0;
else{
preorder(T);
printf("\n");
inorder(T);
printf("\n");
lastorder(T);
printf("\n");
dfs(T);
return 0;
}
}
二叉树的建立和四种遍历办法(前序,中序,后序,层次遍历)
最新推荐文章于 2023-02-28 21:39:17 发布