Input an integer array to determine whether the array is the result of a post-order traversal of a binary search tree. If yes, output Yes, otherwise output No. Suppose any two numbers of the input array are different from each other.
C++:
1 class Solution { 2 public: 3 bool VerifySquenceOfBST(vector<int> sequence) { 4 if (sequence.empty()) 5 return false ; 6 return Verify(sequence , 0 , sequence.size()-1) ; 7 } 8 9 bool Verify(vector<int> sequence, int left , int right) { 10 if (right - left <= 0) 11 return true ; 12 int rootValue = sequence[right] ; 13 int cutIndex = left ; 14 for(; cutIndex < right ; cutIndex++){ 15 if (sequence[cutIndex] > rootValue) 16 break ; 17 } 18 for(int i = cutIndex ; i < right ; i++){ 19 if (sequence[i] < rootValue) 20 return false ; 21 } 22 return Verify(sequence , left , cutIndex-1) && Verify(sequence , cutIndex , right-1) ; 23 } 24 };