首页 > 其他 > 详细

剑指offer-面试题33-二叉搜索树的后序遍历序列-二叉树遍历

时间:2019-11-27 20:43:23      阅读:64      评论:0      收藏:0      [点我收藏+]
/*
题目:
	给定一个序列,判断它是否为某个二叉搜索树的后序遍历。
*/
/*
思路:
	二叉搜索树:左子树<根节点<右子树。
	序列的最右端为根节点,小于根节点的左半部分为左子树,大于根节点的右半部分为右子树。
	递归法,判断是否为合法的二叉搜索树。
*/
#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;

}

    

剑指offer-面试题33-二叉搜索树的后序遍历序列-二叉树遍历

原文:https://www.cnblogs.com/buaaZhhx/p/11945243.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!