寒假训练--树与二叉树--基本操作

来源:互联网 发布:mac 16g内存 虚拟机 编辑:程序博客网 时间:2024/06/06 07:21
#include <stdio.h>
#include <string.h>
typedef struct node{
    char data;
    node *lchile , *rchile ;
}*tree;
//已知前序和中序
struct node *gettree1(tree &t,char *s1,char *s2,int n)
{
    if( n <= 0) return NULL;
    int p = strchr(s1,s2[0])-s1;
    t = new node;
    t->data = s2[0] ;
    t->lchile = gettree1(t->lchile,s1,s2+1,p);
    t->rchile = gettree1(t->rchile,s1+p+1,s2+p+1,n-p-1);
    return t ;
}
//已知中序和后序
struct node *gettree2(tree &t,char *s1,char *s2,int n)
{
    if(n <= 0) return NULL;
    int p = strchr(s1,s2[n-1])-s1;
    t = new node;
    t->data = s2[n-1];
    t->lchile = gettree2(t->lchile,s1,s2,p);
    t->rchile = gettree2(t->rchile,s1+p+1,s2+p,n-p-1);
    return t;
}
//求二叉树的深度
int deeptree(tree t)
{
    if(!t)
        return 0;
    else
    {
        int dl = deeptree(t->lchile);
        int dr = deeptree(t->rchile);
        return dl > dr ? dl+1:dr+1;
    }
}
//叶子数
int ans;
void leaf(tree t)
{
    if(t)
    {
        if(t->lchile && t->rchile )
            ans++;
        leaf(t->lchile);
        leaf(t->rchile);
    }
}
int main()
{
    char s1 , s2 ;
    tree head;
    scanf("%s%s", s1,s2);
    gettree1(head,s1,s2,strlen(s1));
    gettree2(head,s1,s2,strlen(s1));
}
0 0
原创粉丝点击