美文网首页
面试题33:二叉搜索树的后序遍历序列

面试题33:二叉搜索树的后序遍历序列

作者: scott_alpha | 来源:发表于2019-10-07 21:32 被阅读0次

    题目:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回true,否则返回false。
    思路:先在末尾找到根节点,从数组头部遍历,左子树默认应该都小于根节点,当遍历到某个数大于根节点,则为右子树。依次递归遍历。
    解决方案:

    public class Question33 {
        public static boolean verifySequenceOfBST(int[] sequence){
            if (sequence == null || sequence.length <= 0) return false;
            return verifySequenceOfBST(sequence, 0, sequence.length - 1);
        }
        private static boolean verifySequenceOfBST(int[] sequence, int start, int end){
            if (start >= end) return true;
            int root = sequence[end];
            int i = start;
            while (sequence[i] < root){
                i++;
            }
            int j = i;
            while (j < end){
                if (sequence[j] < root){
                    return false;
                }
                j++;
            }
            boolean left = verifySequenceOfBST(sequence, start, i - 1);
            boolean right = verifySequenceOfBST(sequence, i, end - 1);
            return left && right;
        }
    
        public static void main(String[] args) {
            int[] sequence = new int[]{5,7,6,9,11,10,8};
            System.out.println(verifySequenceOfBST(sequence));
        }
    }
    

    相关文章

      网友评论

          本文标题:面试题33:二叉搜索树的后序遍历序列

          本文链接:https://www.haomeiwen.com/subject/jlxvpctx.html