zoukankan      html  css  js  c++  java
  • 剑指offer:面试题24、二叉搜索树的后续遍历序列

    题目描述

    输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。

    代码示例

    public class Offer24 {
        public static void main(String[] args) {
            int[] postSeq = {1, 3, 2};
            Offer24 testObj = new Offer24();
            System.out.println(testObj.verifyPostSeqOfBST(postSeq));
        }
    
        public boolean verifyPostSeqOfBST(int[] seq) {
            if (seq == null || seq.length == 0)
                return false;
            return verifyPostSeqOfBST(seq, 0, seq.length - 1);
        }
    
        private boolean verifyPostSeqOfBST(int[] seq, int left, int right) {
            if (right - left <= 1) {
                return true;
            }
            int rootVal = seq[right];
            int curIndex = left;
            while (curIndex < right && seq[curIndex] <= rootVal)
                curIndex++;
            for (int i = curIndex; i < right; i++) {
                if (seq[i] < rootVal) {
                    return false;
                }
            }
            return verifyPostSeqOfBST(seq, left, curIndex - 1)
                    && verifyPostSeqOfBST(seq, curIndex, right - 1);
        }
    }
    
  • 相关阅读:
    Yeelink 初探
    Macbook被格式化之后
    linux 代码分析工具 gprof
    Writing Clean Code 读后感
    0 bug 读后感
    STM32 控制红外线收发
    HomeKit 与老旧设备
    树莓派控制红外线收发
    苹果没法删除部分照片的问题
    route处理
  • 原文地址:https://www.cnblogs.com/ITxiaolei/p/13167098.html
Copyright © 2011-2022 走看看