输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
若是,则对其任意子树的序列,其末尾元素大于序列中的前若干个元素,而小于其他元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| class Solution { public: bool VerifySquenceOfBST(vector<int> sequence) { if (sequence.size() == 0) { return false; } else if (sequence.size() == 1) { return true; } else { const int root = sequence[sequence.size() - 1]; bool is_left_part = true; int first_right_index = -1; for (int i = 0; i < sequence.size(); i++) { if (is_left_part) { if (sequence[i] > root) { first_right_index = i; is_left_part = false; } } else { if (sequence[i] < root) { return false; } } } if (first_right_index <= 0) { return VerifySquenceOfBST(vector<int>(sequence.begin(), sequence.begin() + sequence.size() - 1)); } else { return VerifySquenceOfBST(vector<int>(sequence.begin(), sequence.begin() + first_right_index)) \ && VerifySquenceOfBST(vector<int>(sequence.begin() + first_right_index, sequence.end())); } } } };
|