二叉搜索树的后序遍历序列
题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
因为后序遍历,所以数组最后一个数字一定是root
注意:如果sequence是[5,4,3,2,1]也有可能是二叉搜索树,即1是根节点,其他的都是纯右子树
public boolean fun(int[] sequence) {
if(sequence.length==0)
return false;
if(sequence.length==1)
return true;
return ju(sequence, 0, sequence.length-1);
}
public boolean ju(int[] a, int low, int high) {
if(low >= high)
return true;
int index = low;
while (index < high) {
if (a[index] < a[high])
index++;
else
break;
}
for (int i = index; i < high; i++) {
if(a[i] < a[high])
return false;//说明此时后面的元素比根节点小了,错误
}
return ju(a, low, index - 1) && ju(a, index, high - 1);
}
浙公网安备 33010602011771号