#include<iostream>
#include<cstdio>
#include<cstring>
#define maxn 1111
using namespace std;
struct Tree
{
Tree *lchild,*rchild;
char data;
};
Tree* buildbypre(Tree *t)
{
char c;
cin>>c;
if(c=='#') return NULL;
t=new Tree;
t->data=c;
t->lchild=buildbypre(t->lchild);
t->rchild=buildbypre(t->rchild);
return t;
}
void preorder(Tree *t)
{
if(t==NULL) return ;
cout<<t->data;
preorder(t->lchild);
preorder(t->rchild);
}
void postorder(Tree* t)
{
if(t==NULL) return ;
postorder(t->lchild);
postorder(t->rchild);
cout<<t->data;
}
void inorder(Tree *t)
{
if(t==NULL) return ;
inorder(t->lchild);
cout<<t->data;
inorder(t->rchild);
}
Tree* postpointbypre(Tree *t)//前序遍历尾点
{
Tree *p=t;
if(t==NULL) return NULL;
while(p->lchild||p->rchild)//一直往右边找,右边找不到,就往左边
{
if(p->rchild) p=p->rchild;
else if(p->lchild) p=p->lchild;
}
return p;
}
Tree*prepointbypost(Tree *t)//后序遍历首点
{
Tree *p=t;
if(t==NULL) return NULL;
while(p->lchild||p->rchild)
{
if(p->lchild) p=p->lchild;
else if(p->rchild) p=p->rchild;
}
return p;
}
Tree *prepointbyin(Tree *t)//中序遍历首点
{
Tree *p=t;
if(t==NULL) return NULL;
while(p->lchild) p=p->lchild;//最左边那个点
return p;
}
Tree *postpointbyin(Tree* t)//中序遍历尾点
{
Tree *p=t;
if(t==NULL) return NULL;
while(p->rchild) p=p->rchild;
return p;
}
int main()
{
Tree *t,*p;
t=buildbypre(t);
cout<<"前序遍历"<<endl;
preorder(t);
cout<<endl;
p=postpointbypre(t);
cout<<"前序遍历尾点值为"<<p->data<<endl;
cout<<"后序遍历"<<endl;
postorder(t);
cout<<endl;
p=prepointbypost(t);
cout<<"后序遍历首点为"<<p->data<<endl;
cout<<"中序遍历"<<endl;
inorder(t);
cout<<endl;
p=prepointbyin(t);
cout<<"中序遍历首点为"<<p->data<<endl;
p=postpointbyin(t);
cout<<"中序遍历尾点为"<<p->data<<endl;
return 0;
}
二叉树首尾点的寻找
最新推荐文章于 2021-12-02 21:12:40 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)