天天看点

树-二叉搜索树的后序遍历序列-JZ23

描述

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则返回true,否则返回false。假设输入的数组的任意两个数字都互不相同。(ps:我们约定空树不是二叉搜索树)

示例1

输入: [4,8,6,12,16,14,10]

返回值: true

思路

1.二叉搜索树:左子树全部小于根节点,右子树全部大于根节点

2.后序遍历:左子树 -> 右子树 -> 根节点,做后一个节点是根节点

3.我们可以将一个序列划分为3段, 左子树+右子树+根, 例如[4, 8, 6, 12, 16, 14, 10]可以根据根节点的值将其划分为左子树[4, 8, 6], 右子树[12, 16, 14], 根[10],

4.代码中可以先确定的右子树区间, 因此当左子树区间中出现大于根节点的值时, 序列不合法, 我们再采用分治的思想, 对于每段序列代表的子树, 检查它的左子树和右子树, 当且仅当左右子树都合法时返回true

代码

public class Solution {
    public boolean VerifySquenceOfBST(int [] sequence) {
        if(sequence == null || sequence.length == 0) {
            return false;
        }
        return check(sequence, 0, sequence.length - 1);
    }
    //检查数组中left到right是不是二叉搜索树
    public boolean check(int [] sequence, int left, int right) {
        if (left >= right) {
            //只有一个节点
            return true;
        }
        int root = sequence[right];
        int index = right - 1;//定义的左子树的右边界
        while (index >= 0 && sequence[index] > root) {
            index--;
        }
        //检查左子树是否有大于根节点的
        for (int i = left; i <= index; i++) {
            if (sequence[i] > root) {
                return false;
            }
        }
        return check(sequence, left, index) && check(sequence, index+1, right-1);
    }
}
           

继续阅读