题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
1 class Solution { 2 public: 3 bool judge(vector<int>& a,int l,int r) 4 { 5 if(l>=r) return true;//为什么是l>=r呢?比如 1435,没有右子树的话,最后 i=r > r-1 6 int temp=a[r]; 7 int i=r,j; 8 while(i>l&&a[i-1]>temp) i--; 9 for(j=i-1;j>=l;j--) 10 { 11 if(a[j]>temp) return false; 12 } 13 return judge(a,l,i-1)&&judge(a,i,r-1); 14 } 15 bool VerifySquenceOfBST(vector<int> sequence) { 16 if(sequence.size()==0) return false; 17 return judge(sequence,0,sequence.size()-1); 18 } 19 };