注意一些特殊情况的处理
bool res = true;
pair<int, int> traverse(vector<int>& postorder, int beg, int end)
{
// base case
if (beg > end || !res)
{
return { INT_MAX,INT_MIN };
}
if (beg == end)
{
return { postorder[beg],postorder[beg] };
}
int rootVal = postorder[end];
int rightBeg = beg;
while (rightBeg != end && postorder[rightBeg] < rootVal)
{
++rightBeg;
}
pair<int, int> left = traverse(postorder, beg, rightBeg - 1);
pair<int, int> right = traverse(postorder, rightBeg, end - 1);
if (left.second >= rootVal || right.first <= rootVal)
{
res = false;
return { INT_MIN,INT_MAX };
}
// 注意排除左右子树可能为空的情况
return { left.first == INT_MAX ? rootVal : left.first, right.second == INT_MIN ? rootVal : right.second };
}
bool verifyPostorder(vector<int>& postorder) {
int n = postorder.size();
traverse(postorder, 0, n - 1);
return res;
}