二叉树的遍历,建立,叶子节点数,高度

#include<bits/stdc++.h>
using namespace std;
const int N = 1010;
char pre[N],mid[N],post[N];
struct node
{
    char data;
    node *l,*r;
};
int cnt=0,z=0;
node *buildtree()  //只用先序遍历建树
{
    node *root;
    if(pre[cnt]==',')
    {
        root=NULL;
        cnt++;
    }
    else
    {
        root=new node;
        root->data=pre[cnt++];
        root->l=buildtree();
        root->r=buildtree();
        if(root->l==NULL&&root->r==NULL)  //叶子节点的个数
        {
            z++;
        }
    }
    return root;
}
node *buildtree(char *pre,char *mid,int *len)//前序中序建立
{
    struct node *root;
    int i;
    if(n == 0)
        return NULL;
    root=new node;
    root->data=pre[0];
    for(i = 0;i < n;i++)
    {
        if(mid[i] == pre[0])
            break;
    }
    root->l=buildtree(pre+1,mid,len);
    root->r=buildtree(pre+i+1,mid+i+1,len-i-1);
    return root;
}
node *buildtree(char *mid,char *post,int len)//中序后序建立
{
    struct node *root;
    int i;
    if(len == 0)
        return NULL;
    root=new node;
    root->data=post[n-1];
    for(i = 0;i < n;i++)
    {
        if(mid[i] == post[n-1])
            break;
    }
    root->l=buildtree(mid,post,len);
    root->r=buildtree(mid+i+1,post+i,len-i-1);
    return root;
}
void midordedr(node *T)  //中序遍历
{
    if(T!=NULL)
    {
        midordedr(T->l);
        printf("%c",T->data);
        midordedr(T->r);
    }
}
void postorder(node *T)  //后序遍历
{
    if(T!=NULL)
    {
        postorder(T->l);
        postorder(T->r);
        printf("%c",T->data);
    }
}
int treehight(struct node *root)  //求树的高度
{
    int h,lh,rh;
    if(root == NULL)
    {
        h = 0;
    }
    else
    {
        lh = treehight(root->l);
        rh = treehight(root->r);
        if(lh>rh)
            h = lh+1;
        else
            h = rh+1;
    }
    return h;
}
int main()
{
    int k;
    cin>>pre;
    cnt=0;
    node *root=new node;
    root=buildtree();
    midordedr(root);
    printf("\n");
    postorder(root);
    printf("\n");
    printf("%d\n",z);
    k=treehight(root);
    printf("%d\n",k);
    return 0;
}
posted @ 2020-05-19 22:29  jk1901贺凌辉  阅读(182)  评论(0)    收藏  举报