题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
题解
public class Solution {
public boolean VerifySquenceOfBST(int[] a) {
if(a == null || a.length == 0)
return false;
return isBST(a, 0, a.length-1);
}
private boolean isBST(int[] a, int low, int high) {
if(high <= low)
return true;
int i = low;
while(a[i] < a[high]) {
i++;
}
for(int j=i;j<high;j++) {
if(a[j] <= a[high])
return false;
}
return isBST(a, low, i-1) && isBST(a, i, high-1);
}
}
本文介绍了一个算法,用于判断一个整数数组是否为某二叉搜索树的后序遍历结果。通过递归检查左子树和右子树的节点值,确保它们符合二叉搜索树的性质,从而实现对数组的有效验证。
1万+

被折叠的 条评论
为什么被折叠?



