zoukankan      html  css  js  c++  java
  • 剑指 Offer 33. 二叉搜索树的后序遍历序列

    根据二叉搜索树的定义,可以通过递归,判断所有子树的正确性 (即其后序遍历是否满足二叉搜索树的定义) ,若所有子树都正确,则此序列为二叉搜索树的后序遍历。

    终止条件: 当 (l geq r) ,说明此子树节点数量小于等于(1),返回 true ;

    划分左右子树: 遍历后序遍历的 ([l, r]) 区间元素,寻找第一个大于根节点值的节点,索引记为 (k) 。此时,可划分出左子树区间 ([l,k-1])、右子树区间 ([k, r - 1])

    判断是否为二叉搜索树:
    左子树区间 ([l, k-1]) 内的所有节点都应小于根节点的值。
    右子树区间 ([k, r-1]) 内的所有节点都应大于根节点的值。

    class Solution {
    public:
        vector<int> post;
        bool verifyPostorder(vector<int>& postorder) {
            post = postorder;
            if (post.empty()) return true;
            return isPostorder(0, post.size() - 1);
        }
    
        bool isPostorder(int l, int r) {
            if (l >= r) return true;
            
            int root = post[r];
            int k = l;
            while (k < r && post[k] < root) k++;
            
            for (int i = k; i < r; i++) {
                if (post[i] < root)
                    return false;
            }
            
            return isPostorder(l, k - 1) && isPostorder(k, r - 1);
        }
    };
    
  • 相关阅读:
    【bzoj2820】GCD
    【learning】莫比乌斯反演
    【bzoj2151】种树
    【noip模拟】局部最小值
    【learning】多项式乘法&fft
    【learning】二分图最大匹配的König定理
    【noip模拟】2048
    【noip模拟】修长城
    【noip模拟】最小点覆盖
    【noip模拟】Fantasia
  • 原文地址:https://www.cnblogs.com/fxh0707/p/15059210.html
Copyright © 2011-2022 走看看