输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
解题思路:在后序遍历得到的序列中,最后一个数字是树的根节点的值。数组中前面的数字可以分为两部分:第一步分是左子树节点的值,它们都比根节点的值小;第二部分是右节点的值,它们都比根节点的值大。
package jianzhi_offer;
public class P33_Solution {
public boolean VerifySquenceOfBST(int[] sequence) {
if (sequence == null || sequence.length == 0)
return false;
if (sequence.length == 1)
return true;
boolean res = helper(sequence, 0, sequence.length - 1);
return false;
}
public boolean helper(int[] a, int start, int end) {
if (start >= end)
return true;
int i = start;
while (a[i] < a[end])
i++;
for (int j = i; j < end; j++) {
if (a[j] < a[end])
return false;
}
return helper(a, start, i - 1) && helper(a, i, end - 1);
}
public static void main(String[] args) {
}
}