【C/C++】BST树的后序遍历

题目描述:
给定一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。

参考以下这颗二叉搜索树:
     5
    / \
   2   6
  / \
 1   3

示例 1:

输入: [1,6,3,2,5]
输出: false

示例 2:

输入: [1,3,2,6,5]
输出: true

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    // 入口函数,判断输入的整数数组是否是某二叉搜索树的后序遍历结果
    bool verifyPostorder(vector<int>& postorder) {
        // 调用辅助函数 verifyPostorderHelper,传入整数数组、数组起始位置和结束位置
        return verifyPostorderHelper(postorder, 0, postorder.size() - 1);
    }
    
    // 辅助函数,用于递归检查数组是否满足二叉搜索树的后序遍历结果
    bool verifyPostorderHelper(vector<int>& postorder, int start, int end) {
        // 当起始位置大于等于结束位置时,表示只有一个节点或者空树,必然满足条件,返回 true
        if (start >= end) return true;
        
        // 获取根节点的值,根节点位于数组末尾
        int root = postorder[end];
        
        int i = start;
        // 在数组中找到左子树的区间,左子树的所有节点值都小于根节点
        while (postorder[i] < root) ++i;
        
        int j = i;
        // 在数组中找到右子树的区间,右子树的所有节点值都大于根节点
        while (postorder[j] > root) ++j;
        
        // 如果 j 不等于 end,说明右子树部分有小于根节点的值,不符合二叉搜索树的性质,返回 false
        if (j != end) return false;
        
        // 递归检查左右子树是否都满足二叉搜索树的后序遍历结果
        // 左子树的区间为 [start, i-1],右子树的区间为 [i, end-1]
        return verifyPostorderHelper(postorder, start, i - 1) && verifyPostorderHelper(postorder, i, end - 1);
    }
};

int main() {
    // 示例输入数据
    vector<int> postorder1 = {1, 6, 3, 2, 5};
    Solution sol;
    
    // 输出第一个示例的结果
    cout << "Example 1: " << boolalpha << sol.verifyPostorder(postorder1) << endl; // 输出 false
    
    // 示例输入数据
    vector<int> postorder2 = {1, 3, 2, 6, 5};
    
    // 输出第二个示例的结果
    cout << "Example 2: " << boolalpha << sol.verifyPostorder(postorder2) << endl; // 输出 true
    
    return 0;
}

相关推荐

  1. 二叉便利,中

    2024-04-09 16:54:03       28 阅读
  2. leetcode-二叉

    2024-04-09 16:54:03       62 阅读
  3. 二叉

    2024-04-09 16:54:03       45 阅读
  4. 【C/C++】BST

    2024-04-09 16:54:03       34 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-09 16:54:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-09 16:54:03       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-09 16:54:03       87 阅读
  4. Python语言-面向对象

    2024-04-09 16:54:03       96 阅读

热门阅读

  1. 设计模式:责任链模式

    2024-04-09 16:54:03       34 阅读
  2. git分支-分支管理

    2024-04-09 16:54:03       33 阅读
  3. Python模拟退火算法

    2024-04-09 16:54:03       35 阅读
  4. Docker 国内镜像

    2024-04-09 16:54:03       32 阅读
  5. Linux_实用技巧

    2024-04-09 16:54:03       33 阅读
  6. 【接口】HTTP(2) |请求方法及状态码

    2024-04-09 16:54:03       38 阅读
  7. 程序员如何搞副业

    2024-04-09 16:54:03       32 阅读
  8. Leetcode 459. 重复的子字符串

    2024-04-09 16:54:03       32 阅读