亮点是递归构造二叉树,还有就是有一个非常重要的知道点,某个子树后序遍历的最后一个结点一定是该子树的根结点,而中序遍历中左子树全位于根结点的左侧,右子树全位于根结点的右侧 #include <iostream> #include <cstdlib> #include <cstring> using namespace std ; const int maxn = 10000 + 10 ; struct Node { Node * left ; Node * right ; int data ; } ; char str1[maxn*10] , str2[maxn*10] ;//字符串长度有可能很长(空格......) int arr1[maxn] , arr2[maxn] ; int mymin ; int ans ; int count1 = 0 ; int count2 = 0 ; void init()//初始化 { memset( arr1 , 0 , sizeof( arr1 ) ) ; memset( arr2 , 0 , sizeof( arr2 ) ) ; count1 = 0 ; count2 = 0 ; mymin = 2147483647 ; ans = 0 ; return ; } void input()//读入数据 { int len1 = strlen( str1 ) ; int len2 = strlen( str2 ) ; for( int i = 0 ; i < len1 ; ) { if( isdigit( str1[i] ) ) { int num = 0 ; while( isdigit( str1[i] ) ) { num = num * 10 + str1[i] - '0' ; i++ ; } arr1[count1] = num ; // map[num] = count1++ ; count1++ ; } else i++ ; } for( int i = 0 ; i < len2 ; ) { if( isdigit( str2[i] ) ) { int num = 0 ; while( isdigit( str2[i] ) ) { num = num * 10 + str2[i] - '0' ; i++ ; } arr2[count2++] = num ; } else i++ ; } return ; } Node * creatNode( int a )//创建结点 { Node * node = new Node ; node -> data = a ; node -> left = NULL ; node -> right = NULL ; return node ; } //以下是该程序最重要的部分 Node * buildTree( Node * root , int a[] , int b[] , int ab , int ae , int bb , int be ) { if( bb <= be ) { Node * node = creatNode( b[be] ) ; root = node ; int pos = 0 ; for( int i = ab ; i <= ae ; i++ ) if( a[i] == b[be] ) { pos = i ; break ; } //递归构造左子树,pos-ab-1为左子树在数组的长度..... root -> left = buildTree( root -> left , a , b , ab , pos - 1 , bb , bb + pos - ab - 1 ) ; root ->right = buildTree( root -> right , a , b , pos + 1 , ae , bb + pos - ab , be - 1 ) ; return root ; } else return NULL ; } //深度优先模拟先序遍历 void dfs( Node * u , int cur ) { if( u )//若结点不为空 { cur += u -> data ; if( ! u -> left && ! u -> right )//若到到叶子结点 { if( cur < mymin )//得到的和比当前最小的和还小,更新记录叶子数据的数值与当前最小值 { mymin = cur ; ans = u -> data ; } return ; } if( u -> left ) dfs( u -> left , cur ) ; if( u -> right ) dfs( u -> right , cur ) ; } else return ; } int main() { while( gets( str1 ) ) { gets( str2 ) ; init() ; input() ; Node * root = NULL ; root = buildTree( root , arr1 , arr2 , 0 , count1 - 1 , 0 , count2 - 1 ) ; dfs( root , 0 ) ; cout << ans << endl ; } return 0 ; }