先中序建二叉树

来源:互联网 发布:1000base x以太网端口 编辑:程序博客网 时间:2024/06/17 15:10

先中序or中后序建立二叉树

二叉树的顺序

  • 二叉树的顺序(先左后右的顺序,相反顺序相反)
    • 先(根)序遍历
    • 中(根)序遍历
    • 后(根)序遍历

可以根据中序和先序/后序建立二叉树,但是必须要有中序,因为只有这样可以划分左右子树,递归的完成序列的访问。

先序和中序建立二叉树

#include <stdio.h>#include <string.h>#include <stdlib.h>typedef char ElemType;typedef struct node{    ElemType data;    struct node *lchild;    struct node *rchild;}*BiTree, *BiNode;int n;char str1[256];char str2[256];BiTree CreatTree(int s1, int t1, int s2, int t2){    int i;    for(i=s2; i<=t2; i++)    {        if(str1[s1]==str2[i])            break;    }    if(i<=t2)    {        BiTree root=(BiTree)malloc(sizeof(BiNode));        root->data=str2[i];        root->lchild=CreatTree(s1+1, s1+i-s2, s2, i-1);        root->rchild=CreatTree(s1+i+1-s2, t1, i+1, t2);        return root;    }    else    {        return NULL;    }    return 0;}int Depth(BiTree root){    int depth=1;    int depthleft=0;    int depthright=0;    if(!root)    {        return 0;    }    else    {        depthleft=Depth(root->lchild);        depthright=Depth(root->rchild);        depth+=(depthleft>depthright ? depthleft:depthright);    }    return depth;}int main(){    int n;    while(scanf("%d", &n)!=EOF)    {        scanf(" %s", str1);        scanf(" %s", str2);        BiTree root;        int num=0;        root=CreatTree(0, n-1, 0, n-1);        num=Depth(root);        printf("%d\n", num);    }    return 0;}

中序和后序建立二叉树

#include <stdio.h>#include <string.h>#include <stdlib.h>typedef char ElemType;typedef struct node{    ElemType data;    struct node *rchild;    struct node *lchild;}*BiTree, BiNode;char str1[345];char str2[345];BiTree CreatTree(int s1, int t1, int s2, int t2){    int i;    for(i=s1; i<=t1; i++)    {        if(str1[i]==str2[t2])            break;    }    if(i<=t1)    {        BiTree root=(BiTree)malloc(sizeof(BiNode));        root->data=str1[i];        root->lchild=CreatTree(s1,i-1, s2, s2+i-s1-1 );        root->rchild=CreatTree(i+1,t1, s2+i-s1, t2-1);        return root;    }    else    {        return NULL;    }    return 0;}int fow(BiTree root){    if(root)    {        fow(root->lchild);        printf("%c",root->data);        fow(root->rchild);    }    return 0;}int Depth(BiTree root){    int depth=1;    int depthleft=0;    int depthright=0;    if(!root)    {        return 0;    }    else    {        depthleft=Depth(root->lchild);        depthright=Depth(root->rchild);        depth+=(depthleft>depthright ? depthleft:depthright);    }    return depth;}int main(){    int n;    scanf("%d", &n);    int i;    int num=0;    for(i=0; i<n; i++)    {        scanf(" %s", str1);        scanf(" %s", str2);        BiTree root;        printf("%d %d\n", sizeof(str1), sizeof(str2));        root=CreatTree(0, strlen(str1)-1, 0, strlen(str2)-1);        //root=CreatTree(0, sizeof(str1)-1, 0, sizeof(str2)-1);        //fow(root);        num=Depth(root);        printf("%d\n", num);    }    return 0;}

补充一点:忘记了strlen()和sizeof()的作用,浪费了大量时间,在建立二叉树的过程中。


原创粉丝点击