二叉搜索树的后序遍历
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6,5]
输出: true
提示:
数组长度 <= 1000
通过次数51,088提交次
通过搜索二叉树的特性实现,搜索二叉树左子树比根节点小,右子树比根节点大;且搜索二叉树的左右子树都是搜索二叉树
class Solution { private: bool verifyPostorderCore(const vector<int>& postorder, int start, int end) { if(start >= end) { return true; } int i = end - 1; while (i >= start && postorder[i] > postorder[end]) { --i; } int j = start; while (j < i) { if (postorder[j] > postorder[end]) { return false; } else { ++j; } } return verifyPostorderCore(postorder, start, i) && verifyPostorderCore(postorder, i + 1, end - 1); } public: bool verifyPostorder(vector<int>& postorder) { if(postorder.empty() || postorder.size() == 1) { return true; } return verifyPostorderCore(postorder, 0, postorder.size() - 1); } };