二叉树首尾点的寻找

来源:互联网 发布:mac照片如何归类 编辑:程序博客网 时间:2024/04/30 05:38
#include<iostream>#include<cstdio>#include<cstring>#define maxn 1111using 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;}

0 0
原创粉丝点击