You are to determine the value of the leaf node in a given binary tree that is the terminal node of a path of least value from the root of the binary tree to any leaf. The value of a path is the sum of values of nodes along that path.
Input
The input file will contain a description of the binary tree given as the inorder and postorder traversal sequences of that tree. Your program will read two line (until end of file) from the input file. The first line will contain the sequence of values associated with an inorder traversal of the tree and the second line will contain the sequence of values associated with a postorder traversal of the tree. All values will be different, greater than zero and less than 10000. You may assume that no binary tree will have more than 10000 nodes or less than 1 node.
Output
For each tree description you should output the value of the leaf node of a path of least value. In the case of multiple paths of least value you should pick the one with the least value on the terminal node.
1 #include<cstdio> 2 #include<cstring> 3 struct node 4 { 5 int lch,rch; 6 }a[10010]; 7 int zx[10010],hx[10010],n,ans=0x7f7f7f7f,ans_leaf=0x7f7f7f7f; 8 bool rdzx() 9 { 10 int i,j,k,p,q,x,y,z; 11 char c; 12 if (scanf("%d",&zx[1])==-1) return 0; 13 n=1; 14 while (scanf("%c",&c)&&c==' ') 15 scanf("%d",&zx[++n]); 16 return 1; 17 } 18 void rdhx() 19 { 20 int i; 21 for (i=1;i<=n;i++) 22 scanf("%d",&hx[i]); 23 } 24 int crt(int lz,int rz,int lh,int rh) 25 { 26 if (lz>rz) return 0; //注意终止条件 27 int i,j,k,p,q,x,y,z; 28 p=hx[rh]; 29 i=lz; 30 while (zx[i]!=p) i++; 31 a[p].lch=crt(lz,i-1,lh,i+lh-lz-1); //关键在于这两个式子的推导,列方程求比较不费脑子 32 a[p].rch=crt(i+1,rz,rh-rz+i,rh-1); 33 return p; 34 } 35 void sc(int p,int x) 36 { 37 int i,j,k,l,m,y,z; 38 x+=p; 39 if (!a[p].lch&&!a[p].rch) 40 { 41 if (x<ans||(x==ans&&p<ans_leaf)) 42 { 43 ans=x; 44 ans_leaf=p; 45 return; 46 } 47 } 48 if (a[p].lch) sc(a[p].lch,x); 49 if (a[p].rch) sc(a[p].rch,x); 50 } 51 int main() 52 { 53 int i,j,k,l,m,p,q,x,y,z; 54 while (rdzx()) 55 { 56 rdhx(); 57 memset(a,0,sizeof(a)); 58 crt(1,n,1,n); 59 ans=ans_leaf=0x7f7f7f7f; 60 sc(hx[n],0); 61 printf("%d ",ans_leaf); 62 } 63 }
递归求树,由于后序遍历的最后一个元素一定是根,所以可以在中序中找到根的位置,则其左边为左子树,右边为右子树,分治求解。
求值相对简单,dfs即可。