剑指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;

}

    

猜你喜欢

转载自www.cnblogs.com/buaaZhhx/p/11945243.html