Fork me on GitHub

二叉搜索树的后序遍历序列

题目描述

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。

解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public:
bool VerifyBST(vector<int> seq,int begin,int end){
if(seq.empty() || begin > end) return false;

int root = seq[end];
//在二叉搜索树中左子树的结点小于根结点
int i=0;
for(;i<end;++i){
if(root < seq[i]){
break;
}
}

for(int j=i;j<end;++j){
if(root > seq[j]){
return false;
}
}

bool left = true;
if(i>begin){
left = VerifyBST(seq,begin,i-1);
}

bool right = true;
if(i<end-1){
right = VerifyBST(seq,i,end-1);
}
return left && right;
}

bool VerifySquenceOfBST(vector<int> sequence) {
return VerifyBST(sequence,0,sequence.size()-1);
}


};

本文标题:二叉搜索树的后序遍历序列

文章作者:LiuXiaoKun

发布时间:2019年02月27日 - 21:02

最后更新:2019年02月27日 - 21:02

原始链接:https://LiuZiQiao.github.io/2019/02/27/二叉搜索树的后序遍历序列/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%