题目链接
题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6,5]
输出: true
解题思路
看一下自己写的博客【算法】【树】先序先序、后序序列是否为BST树的先序序列、后序序列(详细解释)_Elephant_King的博客-CSDN博客
题解
class Solution {
public:
bool judge(int begin,int root,vector<int>& postorder){
if(begin>=root) return true;
int p=begin;
while(postorder[p]<postorder[root]) p++;
int m=p;
while(postorder[p]>=postorder[root]&&p<root) p++;
return root==p&&judge(begin,m-1,postorder)&&judge(m,root-1,postorder);
}
bool verifyPostorder(vector<int>& postorder) {
return judge(0,postorder.size()-1,postorder);
}
};