题目链接:leetcode.
二叉搜索树后序遍历 [左子树 | 右子树 | 根节点]
且左子树都小于根节点,右子树都大于根节点
左右子树内部依然满足这样的条件
所以使用递归:
/*
执行用时:4 ms, 在所有 C++ 提交中击败了49.55%的用户
内存消耗:6.7 MB, 在所有 C++ 提交中击败了95.77%的用户
*/
class Solution {
public:
bool isPostorder(vector<int>& postorder, int start, int end)
{
if(end - start < 2)
return true;
int mid = start;
while(postorder[mid] < postorder[end])
mid++;
for(int i = mid;i < end;++i)
{
if(postorder[i] < postorder[end])
return false;
}
return isPostorder(postorder,start,mid-1) && isPostorder(postorder,mid,end-1);
}
bool verifyPostorder(vector<int>& postorder) {
int N = postorder.size();
if(N < 3)
return true;
return isPostorder(postorder, 0, N - 1);
}
};
大佬还说了个时间复杂度能降到O(n)的方法,单调栈,我没太看懂。