题目:二叉搜索树的后序遍历序列
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6,5]
输出: true
提示:数组长度 <= 1000
解题:
方法一:递归
已知条件: 后序序列最后一个值为root;二叉搜索树左子树的值都比root小,右子树的值都比root大。
步骤:
- 确定根节点root;
- 遍历序列(除去root结点),找到第一个大于root的位置,则该位置左边为左子树,右边为右子树;
- 遍历右子树,若发现有小于root的值,则直接返回false;
- 分别判断左子树和右子树是否仍是二叉搜索树(即递归步骤1、2、3)。
class Solution {
public:
bool verifyPostorder(vector<int>& postorder) {
bool res = true;
if (postorder.empty())
return res;
res = helper(postorder,0,postorder.size()-1);
return res;
}
bool helper(vector<int>& postorder, int start, int end)
{
if (postorder.empty() || start > end)
return true;
//根结点
int root = postorder[end];
//在二叉搜索树中左子树的结点小于根结点
int i = start;
for(;i<end;i++)
{
if (postorder[i] > root)
break;
}
//在二叉搜索书中右子树的结点大于根结点
for(int j = i;j<end;j++)
{
if (postorder[j] < root)
return false;
}
//判断左子树是不是二叉搜索树
bool left = true;
if (i>start)
{
left = helper(postorder,start,i-1);
}
//判断右子树是不是二叉搜索树
bool right = true;
if (i<end-1)
{
right = helper(postorder, i,end-1);
}
return left && right;
}
};
方法二:
class Solution {
bool helper(vector<int>& post,int lo, int hi){
if(lo >= hi) return true; //单节点或空节点返回true
int root = post[hi]; //后序遍历序列最后的值为根节点的值
int l = lo;
while(l<hi && post[l]<root)
l++; //遍历左子树(值小于根),左子树序列post[lo, l);
int r = l;
while(r<hi && post[r]>root)
r++; //遍历右子树(值大于根),右子树序列post[l, r);
if(r != hi) return false;//若未将post[l, hi)遍历完,则非后序遍历序列 返回false
return helper(post, lo, l-1) && helper(post, l, hi-1); //递归检查左右子树
}
public:
bool verifyPostorder(vector<int>& postorder) {
return helper(postorder,0,postorder.size()-1);
}
};