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");
}
}