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

    /*
    题目:
    	给定一个序列,判断它是否为某个二叉搜索树的后序遍历。
    */
    /*
    思路:
    	二叉搜索树:左子树<根节点<右子树。
    	序列的最右端为根节点,小于根节点的左半部分为左子树,大于根节点的右半部分为右子树。
    	递归法,判断是否为合法的二叉搜索树。
    */
    #include<iostream>
    #include<string.h>
    #include<algorithm>
    #include<cmath>
    #include<stdio.h>
    #include<vector>
    #include<stack>
    #include<queue>
    
    using namespace std;
    
    bool verify(const vector<int> &sequence, int start,int end){
        if(start == end) return true;
    
        int root = sequence[end];
        int separation = start;
        for(; separation < end; separation++){
            if(sequence[separation] > root){
                break;
            }
        }
        for(int index = separation; index < end; index++){
            if(sequence[index] < root){
                return false;
            }
        }
        bool left = true;
        if(separation > start){
            left = verify(sequence,start,separation-1);
        }
        bool right = true;
        if(separation < end){
            right = verify(sequence,separation,end - 1);
        }
        return left&&right;
    }
    
    bool VerifySquenceOfBST(vector<int> sequence) {
        if(sequence.empty()) return false;
        int length = sequence.size();
        return verify(sequence,0,length-1);
    }
    
    int main(){
        vector<int> a = {7,4,6,5};
        cout<<VerifySquenceOfBST(a)<<endl;
    
    }
    

        

  • 相关阅读:
    ASP.NET MVC 中的视图生成
    atm
    Oracle 客户端 NLS_LANG 的设置(转)
    log4jdbc
    java基本类型作为成员变量时的初始值
    使用activeMQ实现jms
    JAVA反射机制
    [notes] ImageNet Classification with Deep Convolutional Neual Network
    cocos2d-x3.0 ListView
    Mean Shift具体介绍
  • 原文地址:https://www.cnblogs.com/buaaZhhx/p/11945243.html
Copyright © 2011-2022 走看看