解法一
递归
遍历本层数组,找到比根节点(即数组最后一个数)大的第一个节点,此节点向左都是左子树,此节点向右都是右子树
class Solution {
public:
bool verifyPostorder(vector<int>& postorder) {
if(postorder.size()==0) return true;
return rever(postorder, 0 ,postorder.size()-1);
}
bool rever(vector<int>& postorder, int left, int right){
if(left>=right) return true;
int i;
for (i = 0; i < right; i++)
{
if(postorder[i]>postorder[right]) break;
}
for ( int j = i+1; j< right; j++)
{
if(postorder[j]<postorder[right]) return false;
}
return rever(postorder,left,i-1)&& rever(postorder,i,right-1);
}
};
解法二
栈
将数组翻转,则顺序为“根右左”,如果我们使用单调栈存储根节点和右子树,当遇到左子树时,左子树节点肯定比根节点和右子树小,依次出栈,并更新root节点。如果root节点小于即将入栈的元素,说明顺序错误,直接返回失败。
class Solution {
public:
bool verifyPostorder(vector<int>& postorder) {
if(postorder.size()==0) return true;
stack<int> s;
int root = INT_MAX;
for (int i = postorder.size()-1; i>=0; i--)//注意是逆序,从最大开始倒推
{
if(postorder[i]> root) return false;
while(!s.empty() && s.top()>postorder[i] ){
root=s.top();
s.pop();
}
s.push(postorder[i]);
}
return true;
}
};