版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/arthu6/article/details/81058566
<代码>
#include<iostream>
#include<queue>
using namespace std;
//创建节点
struct Tnode
{
char data;//数据域
Tnode *rchild;//右孩子
Tnode *lchild;//左孩子
};
//创建二叉树
void CreatTree(Tnode *&T)//递归建树
{
char a;
cin>>a;
if(a!='#')//#号表示为空
{
T=new Tnode();//加小括号的作用<分配内存并初始化>,去之会产生野指针
T->data=a;
CreatTree(T->lchild);//生成左子树
CreatTree(T->rchild);//生成右子树
}
}
//前序遍历
void PreOder(Tnode *root)
{
if(root)
{
cout<<root->data<<" ";//输出父亲节点
PreOder(root->lchild);//输出左子树
PreOder(root->rchild);//输出右子树
}
}
//中序遍历
void InOder(Tnode *root)
{
if(root)
{
InOder(root->lchild);
cout<<root->data<<" ";
InOder(root->rchild);
}
}
//后序遍历
void PosOder(Tnode *root)
{
if(root)
{
PosOder(root->lchild);
PosOder(root->rchild);
cout<<root->data<<" ";
}
}
//层序遍历
//采用队列输出一节点的同时将其左右孩子入队,重复操作直至队列为空
void LeverOder(Tnode *root)
{
if(root)
{
queue<Tnode*> Q;
Q.push(root);
while(!Q.empty())
{
Tnode *q=Q.front();
Q.pop();
cout<<q->data<<" ";
if(q->lchild!=NULL) Q.push(q->lchild);
if(q->rchild!=NULL) Q.push(q->rchild);
}
}
}
//树高
int Depth(Tnode *root)
{
if(root==NULL) return 0;
int ldeep=Depth(root->lchild)+1;//计算左子树高度并加1
int rdeep=Depth(root->rchild)+1;//计算右子树高度并加1
return ldeep>rdeep?ldeep:rdeep;//返回最大高度
}
//中序查找节点
Tnode *InOderSearch(Tnode *root,char s)
{
if(root)
{
if(s==root->data) return root;//节点即为所找
Tnode *l=NULL;
l=InOderSearch(root->lchild,s);//在左子树上查找
if(l) return l;
Tnode *r=NULL;
r=InOderSearch(root->rchild,s);//在右子树上查找
if(r) return r;
if(!l&&!r) return NULL;//不存在s
}
}
//查找叶子节点
void searchLeaf(Tnode *r)
{
if(r)
{
if(!r->lchild&&!r->lchild) cout<<r->data<<" ";//如果左右子树为空则输出节点
else
{
searchLeaf(r->lchild);//遍历左子树
searchLeaf(r->rchild);//遍历右子树
}
}
}
//main函数
int main()
{
Tnode *Root=NULL;
Tnode *p=NULL;
char d;
CreatTree(Root);
cout<<endl<<"前序遍历:";
PreOder(Root);
cout<<endl<<"中序遍历:";
InOder(Root);
cout<<endl<<"后序遍历:";
PosOder(Root);
cout<<endl<<"层序遍历:";
LeverOder(Root);
cout<<endl<<"树高:";
cout<<Depth(Root);
cout<<endl<<"输出叶子节点:";
searchLeaf(Root);
cout<<endl<<"输入要查找的节点:";
cin>>d;
p=InOderSearch(Root,d);
if(p) cout<<"Yes"<<endl;//查找成功
else cout<<"No"<<endl;//查找失败
return 0;
}
截图: