nyoj221 nyoj756 重建二叉樹

nyoj221題目鏈接
已知二叉樹前序中序遍歷求二叉樹後序遍歷:已知二叉樹前序中序遍歷可重建二叉樹,進而遍歷後序。

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct  node
{
    char value;
    struct  node*l,*r;
};
node *rebuildtree(char *preorder,char *midorder,int len)//重建二叉樹
{
    if(len<=0)
        return NULL;
    node*tree=( node*)malloc(sizeof( node));
    tree->value=*preorder;//賦值
    char *k=strchr(midorder,tree->value);//查找根節點在中序遍歷中的位置
    int leftlen=strlen(midorder)-strlen(k);//左子樹長度
    int rightlen=len-leftlen-1;//右子樹長度
    tree->l=rebuildtree(preorder+1,midorder,leftlen);  //左子樹
    tree->r=rebuildtree(preorder+leftlen+1,midorder+leftlen+1,rightlen); //右子樹
    return tree;
}
void print(node *tree)//後序遍歷
{
    if(tree==NULL)
        return ;
    print(tree->l);
    print(tree->r);
    printf("%c",tree->value);
}
int main()
{
    char a[30],b[30];
    while(scanf("%s%s",a,b)!=EOF)
    {
        node *root=NULL;
        root=rebuildtree(a,b,strlen(a));
        print(root);
        printf("\n");
    }
}

nyoj756題目鏈接
已知二叉樹中序後序遍歷求二叉樹前序遍歷:已知二叉樹中序後序遍歷可重建二叉樹,進而遍歷前序。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
    char value;
    node *l,*r;
};
node*rebuildtree(char *midorder,char *behindorder,int len) //重建二叉樹
{
    if(len<=0) return NULL;
    node*tree=(node*)malloc(sizeof(node));
    tree->value=behindorder[len-1];  //根節點
    char *position=strchr(midorder,tree->value); //查找根節點在中序遍歷中的位置
    int leftlen=strlen(midorder)-strlen(position);//左子樹長度
    int rightlen=len-leftlen-1;//右子樹長度
    tree->l=rebuildtree(midorder,behindorder,leftlen);//左子樹
    tree->r=rebuildtree(midorder+leftlen+1,behindorder+leftlen,rightlen);//右子樹
    return tree;
}
void print(node*tree)//前序遍歷
{
    if(tree==NULL) return ;
    printf("%c",tree->value);
    print(tree->l);
    print(tree->r);
}
int main()
{
    char midorder[30],behindorder[30];
    while(~scanf("%s%s",behindorder,midorder))
    {
        struct node *root=NULL;
        root=rebuildtree(midorder,behindorder,strlen(midorder));
        print(root);
        printf("\n");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章