二叉搜索树的后序遍历序列
二叉搜索树的后序遍历序列
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
这道题的步骤很简单,就是递归验证序列是否符合二叉搜索树的后序遍历要求。验证的步骤就是:
- 已知最后一个是父节点,前面的左子树,随后的是右子树
- 遍历找到不小于父节点的值的位置
- 遍历保证其后的点的值都不小于父节点
public class Solution {
public boolean helpVerify(int [] sequence, int start, int root){
if(start >= root)return true;
int key = sequence[root];
int i;
//找到左右子数的分界点
for(i=start; i < root; i++)
if(sequence[i] > key)
break;
//在右子树中判断是否含有小于root的值,如果有返回false
for(int j = i; j < root; j++)
if(sequence[j] < key)
return false;
return helpVerify(sequence, start, i-1) && helpVerify(sequence, i, root-1);
}
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence == null || sequence.length == 0)return false;
return helpVerify(sequence, 0, sequence.length-1);
}
}

浙公网安备 33010602011771号