zoukankan      html  css  js  c++  java
  • 判断数组序列是否是二叉搜索树的后序遍历

    #include <iostream>
    using namespace std;
    
    bool isPostorderOfBST(int postorder[], int low, int high)
    {
        if(postorder == NULL || low < 0 || high < 0) return false;
    
        if(low == high) return true;
    
        int pivot = high - 1; // 查找左子树与右子树的分界点
        while(pivot >= 0 && postorder[pivot] > postorder[high])
        {
            --pivot;
        }
    
        int lowIndex = pivot;
        while(lowIndex >= 0 && postorder[lowIndex] < postorder[high])
        {
            --lowIndex;
        }
    
        if(lowIndex >= 0) return false; // 左子树所有元素都比根节点要小
    
        if(pivot + 1 < high && !isPostorderOfBST(postorder, pivot + 1, high - 1)) // 判断右子树
        {
            return false;
        }
    
        if(low <= pivot && !isPostorderOfBST(postorder, low, pivot)) // 判断左子树
        {
            return false;
        }
    
        return true;
    }
    
    int main(int argc, char const *argv[])
    {
        int postorder0[] = {5, 7, 6, 9, 11, 10, 8};
        int postorder1[] = {11, 10, 9, 8, 7, 6, 5};
        int postorder2[] = {5, 6, 7, 8, 9, 10, 11};
        int postorder3[] = {8, 9, 5, 11, 10, 7, 6};
        int postorder4[] = {7, 6, 12, 5, 11, 10, 9};
        cout << "{5, 7, 6, 9, 11, 10, 8}---" << isPostorderOfBST(postorder0, 0, 6) << endl;
        cout << "{11, 10, 9, 8, 7, 6, 5}---" << isPostorderOfBST(postorder1, 0, 6) << endl;
        cout << "{5, 6, 7, 8, 9, 10, 11}---" << isPostorderOfBST(postorder2, 0, 6) << endl;
        cout << "{8, 9, 5, 11, 10, 7, 6}---" << isPostorderOfBST(postorder3, 0, 6) << endl;
        cout << "{7, 6, 12, 5, 11, 10, 9}---" << isPostorderOfBST(postorder4, 0, 6) << endl;
    
        return 0;
    }
  • 相关阅读:
    sql 数据库还原脚本 (kill链接+独占
    最长回文字符串
    UVa 455 Periodic Strings
    UVa 1225 Digit Counting
    UVa 340 Master-Mind Hints
    UVa 10976
    UVa 725
    UVa 11059
    POJ1887 最长下降子序列
    最大连续子序列算法(数组的连续子数组最大和(首尾不相连))
  • 原文地址:https://www.cnblogs.com/fengkang1008/p/4719178.html
Copyright © 2011-2022 走看看