二叉树有前序(中左右)中序(左中右)后序(左右中)三种方式。
可用递归的思路加上链表实现二叉树的创建与遍历。
#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct node{
char data;
struct node*left;
struct node*right;
}Node,*jnode;
jnode creat(jnode &t)//创建二叉树;
{
char a;
cin>>a;
if(a=='#')
{
t=NULL;
}
else
{
t=(jnode)malloc(sizeof(node));
t->data=a;
t->left=creat(t->left);
t->right=creat(t->right);
}
return t;//?????
}
void qianxu(jnode &t)//前序遍历二叉树;
{
if(t)
{
cout<<t->data;
qianxu(t->left);
qianxu(t->right);
}
}
void zhongxu(jnode &t)//中序遍历二叉树;
{
if(t)
{
zhongxu(t->left);
cout<<t->data;
zhongxu(t->right);
}
}
void houxu(jnode &t)
{
if(t)
{
houxu(t->left);
houxu(t->right);
cout<<t->data;
}
}
int shendu(jnode &t)//找出二叉树的深度;
{
int sum=0,depthl,depthr;
if(t==NULL)
{
return 0;
}
else
{
depthl=shendu(t->left);
depthr=shendu(t->right);
sum=1+(depthl>depthr?depthl:depthr);
}
return sum;
}
int jiedian(jnode &t)//计算二叉树的节点数;
{
int sum=0,m,n;
if(t)
{
if(!t->left&&!t->right)
{
sum++;
}
else
{
m=jiedian(t->left);
sum+=m;
n=jiedian(t->right);
sum+=n;
}
}
return sum;
}
int main()
{
cout<<"请输入二叉树:\n";
jnode t;
t=creat(t);
cout<<"输出前序遍历结果\n";
qianxu(t);
cout<<endl;
cout<<"输出中序遍历结果\n";
zhongxu(t);
cout<<endl;
cout<<"输出后序遍历结果\n";
houxu(t);
cout<<endl;
int m=shendu(t);
cout<<"输出二叉树的深度\n";
cout<<m<<endl;
cout<<"输出二叉树的节点数\n";
int l=jiedian(t);
cout<<l<<endl;
return 0;
}
普通的二叉树,节点只需包含三个域,即储存元素的data,储存左右指针的指向节点的指针lchild,rchild。
创建二叉树时同样用到递归,思路是将一棵不完整的二叉树补充完整,空缺的左孩子或有孩子用#做标记,同时令此时的左孩子或有孩子的父节点的左指针或有指针为NULL。即找到了每一次递归结束的标志。
前中后序遍历时的递归,每一次递归转向上一次递归的条件即其左右指针都为空。