输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
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 };
原文地址:https://www.cnblogs.com/mengchunchen/p/8963762.html
时间: 2024-11-05 12:26:06