解题思路:首先根据中序遍历和后序遍历的结果还原二叉树,后序遍历的最后一个数字为根,在中序遍历中找到该根的位置,在其左边为左子树,右边为右子树,据此继续递归进行还原。还原完毕后通过DFS递归遍历,找到最小的边权和,最后打印结果。
题目大意:输入一个二叉树的中序和后序,输出一个叶子节点,该叶子节点到根的数值总和最小。
Sample Input
3 2 1 4 5 7 6
3 1 2 5 6 7 4
7 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5
255
255
Sample Output
1
3
255
#include<cstdio>
#include<iostream>
#include<string.h>
using namespace std;
struct node{
char v;
node *left;
node *right;
}Tree[1000];
int loc;
char str1[1000],str2[1000];
node *creat()
{
Tree[loc].right=Tree[loc].left=NULL;
return &Tree[loc++];
}
node *build(int s1,int e1,int s2,int e2)
{
node *ret=creat();
ret->v=str2[e2];
int countn;
for(int i=s1;i<=e1;i++)
{
if(str1[i]==str2[e2])
{
countn=i;
}
}
if(countn!=s1)
{
ret->left=build(s1,countn-1,s2,s2+countn-s1-1);
}
if(countn!=e1)
{
ret->right=build(countn+1,e1,s2+countn-s1,e2-1);
}
return ret;
}
int maxn;
char maxnum;
void DFS(node *T,int sum) //DFS遍历求得最小边权和
{
if(T->left==NULL&&T->right==NULL)
{
if(sum+T->v-'0'<maxn||(sum+T->v-'0'==maxn&&T->v<maxnum))
{
maxn=sum+T->v-'0';
maxnum=T->v;
//printf("%d %c\n",sum,maxnum);
}
return;
}
if(T->left!=NULL) DFS(T->left,sum+T->v-'0');
if(T->right!=NULL) DFS(T->right,sum+T->v-'0');
}
int main()
{
while(1)
{
loc=0;
scanf("%s%s",str1,str2);
int l1=strlen(str1)-1;
int l2=strlen(str2)-1;
node *T=build(0,l1,0,l2);
maxn=123123123;
maxnum='9';
DFS(T,0);
printf("%d\n",maxn);
printf("%d\n",maxnum-'0');
}
return 0;
}