难度:中等
题目
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6,5]
输出: true
提示:
数组长度 <= 1000
解答
思路
递归。
后序遍历,根节点在最后面。
只要数组可以不断的被根节点分成两部分,左边小于根节点,右边大于根节点。则这个数组是二叉搜索树的后序遍历。
知识点
迭代器的使用
代码
class Solution {
public:
bool verifyPostorder(vector<int>& postorder) {
return verifyPostorderCore(postorder.begin(),postorder.end());
}
bool verifyPostorderCore(vector<int>::iterator begin, vector<int>::iterator end) {
if(end-begin<=1)
{
return true;
}
int root=*(end-1);
vector<int>::iterator mid=end-1;
for(auto it=begin;it<end;it++)
{
if(*it>root)
{
mid=it;
break;
}
}
for(auto it=mid+1;it<end;it++)
{
if(*it<root)
{
return false;
}
}
return (verifyPostorderCore(begin,mid))&&(verifyPostorderCore(mid,end-1));
}
};