zoukankan      html  css  js  c++  java
  • 面试题33:二叉搜索树的后序遍历序列

    二叉搜索树的后序遍历序列。这个题目应该注意二叉搜索树的后序遍历的特征:最后一个值是根节点。

    C++版本

    #include <iostream>
    #include <vector>
    #include <stack>
    #include <cstring>
    #include <string>
    #include <queue>
    #include <algorithm>
    #include "TreeNode.h"
    using namespace std;
    
    // 之字形打印二叉树
    bool VerifySquenceOfBST(vector<int> sequence) {
        int length = sequence.size();
        if(length < 1)
            return false;
        // 根节点
        int root = sequence[length-1];
        int i = 0;
        // 左子树上的所有节点应该都比root小
        for(i = 0; i < length - 1; i++){
            if(sequence[i] > root)
                break;
        }
        int j = i;
        // 右子树上的所有节点应该都比root大
        for(; j < length - 1; j++){
            if(sequence[j] < root)
                return false;
        }
        bool left = true;
        // 前i个数
        if(i > 0){
            vector<int> leftSequence(sequence.begin(), sequence.begin() + i);
            left = VerifySquenceOfBST(leftSequence);
        }
        bool right = true;
        // i到倒数第二个数
        if(i < length - 1){
            vector<int> rightSequence(sequence.begin() + i, sequence.end() - 1);
            right = VerifySquenceOfBST(rightSequence);
        }
        return left && right;
    }
    
    int main()
    {
    
        return 0;
    }
    
  • 相关阅读:
    Linux下c++使用pthread库
    一半,一绊
    【codevs3945】 完美拓印
    【poj2942】 Knights of the Round Table
    【bzoj2730】 HNOI2012—矿场搭建
    【poj1177】 Picture
    Tarjan学习笔记
    联赛总结
    【poj3461】 Oulipo
    【csuoj1014】 西湖三人行
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13393563.html
Copyright © 2011-2022 走看看