Title Description
Enter an integer array to determine whether the array is the result of a traversal of a binary search tree. If yes, output Yes, otherwise output No. Assume that any two numbers in the input array are different from each other.
Analysis:
The legal sequence of the BST sequence is that for a sequence S, the last element is x (that is, the root). If the sequence of the last element is T, then T satisfies: T can be divided into two segments, the previous (Left subtree) is less than x, the next segment (right subtree) is greater than x, and both segments (subtrees) are legal post-order sequences. Perfect recursive definition:).
在这里插入代码片
public boolean VerifySquenceOfBST(int [] s) {
if(s.length==0)
return false;
return istree(s,0,s.length-1 );
}
public boolean istree(int []s,int a,int b) {
if(a>=b)return true;
int i=a,j;
for(;i<b;i++)
if(s[i]>s[b])
break;
j=i;
while(j<b)
{if(s[j]<s[b])
return false;
j++;}
return istree(s,a,i-1)&&istree(s,i,b-1);
}