输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true
,否则返回 false
。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3示例 1:
输入: [1,6,3,2,5]
输出: false示例 2:
输入: [1,3,2,6,5]
输出: true
解题思路:根据二叉搜索树的性质,其根节点左子树上的元素都小于根节点,右子树上的元素都大于根节点,且左右子树均满足此条件。因此可以使用递归的方法,遍历序列的最后一个元素是根节点,从序列开始,找到所有小于根节点的元素序列,该序列是左子树的后序遍历序列,然后记录此位置坐标,继续遍历找到序列中元素均大于根节点的右子树后序遍历序列,然后判断右子树序列的结束角标是否与根节点的角标相同且递归判断左右子树是否满足上述性质。
class Solution {
public boolean verifyPostorder(int[] postorder) {
return verify(postorder,0,postorder.length-1);
}
private boolean verify(int[] postorder,int start,int end){
if(start>=end) return true;
int i=start;
while(postorder[i]<postorder[end]){
i++;
}
int mid = i;
while(postorder[i]>postorder[end]){
i++;
}
return i==end && verify(postorder,start,mid-1) && verify(postorder,mid,i-1);
}
}