题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
public class Solution {
public boolean VerifySquenceOfBST(int[] sequence) {
if (null == sequence || 0 == sequence.length) {
return false;
}
return method(sequence, 0, sequence.length - 1);
}
public boolean method(int[] nums, int begin, int end) {
if (begin >= end) {
return true;
}
int root = nums[end];
int smallCount = 0;
boolean small = true;
for (int i = begin; i < end; i++) {
if(nums[i] < root){
if(small){
smallCount++;
} else {
return false;
}
} else {
small = false;
}
}
return method(nums, begin, begin + smallCount - 1) && method(nums, begin + smallCount, end - 1);
}
}
本文介绍了一个算法,用于判断一个整数数组是否为某二叉搜索树的后序遍历结果。通过递归方法,检查数组是否满足二叉搜索树的特性,即所有左子树节点小于根节点,所有右子树节点大于根节点。
704

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



