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的JVM可以从SUN网站上下载
    实践是最好的老师
    SCAU 8624 多项式系数累加和
    SCAU 8617 阶乘数字和 (水题)
    SCAU 8614 素数
    SCAU 8619 公约公倍
    HDU ACM 1106 排序
    Uva 465 Overflow
    SCAU 8611 大牛之路I
    SCAU 9501 ACMer不得不知道的事儿
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13393563.html
Copyright © 2011-2022 走看看