Meaning of the questions:
Given sequence preorder and, to a number, this number to find the location in the tree and outputs it in the left subtree of the maximum number, if this number is not in the tree, the output of -1
Sample input:
9
20 15 10 12 18 16 17 25 30
10 12 15 16 17 18 20 25 30
Sample output:
15
Code:
#include<iostream> #include<algorithm> using namespace std; struct Tree { int data; struct Tree *left,*right; }; int a[105]; int b[105]; int mm=0; Tree *Pre_and_in(int *pre,int *in,int n){ Tree *b; int *p; int k; if(n<=0 ) return NULL; B = (Tree *) the malloc ( the sizeof (Tree)); B -> * Data = pre; // to find the root node in the sequence in the sequence for (P = in ; P < in + n-; ++ P ) { IF (* P * == pre) BREAK ; } K = p- in ; // statistical left subtree of the root nodes in = 0, p = root index b-> left = Pre_and_in (pre + . 1 , in , K); B -> right = Pre_and_in (pre + K + . 1 , P + . 1 , NK-1); return b; } void dfs(Tree*T){//找x的左子树最大的数 if(T){ if(mm<T->data) mm=T->data; if(T->left) dfs(T->left); if(T->right) dfs(T->right); } } int search(int x,Tree*T){//先找到x if(T->data==x){ if(T->left) dfs(T->left); else mm=x; return 1; }else{ if(T->left) search(x,T->left); if(T->right) search(x,T->right); } } int main() { struct Tree *T; int n; cin>>n; for(int i=0;i<n;i++) { cin>>a[i]; } for(int i=0;i<n;i++) { cin>>b[i]; } T=Pre_and_in(a,b,n); int x; cin>>x; if(search(x,T)==-1) cout<<"-1"; else cout<<mm; return 0; }