剑指offer66题--Java实现，c++实现和python实现 23.二叉搜索树的后序遍历序列

题目描述

C++

class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
return sequence.size()==0? false:SquenceOfBST(sequence,0,sequence.size());
}

bool SquenceOfBST(vector<int> &sequence, int l, int r)
{
if (l == r)
return true;
int mid = l, last = 0;
for (; mid < r - 1 && sequence[mid] < sequence[r - 1]; ++mid);
for (last = mid; last < r - 1 && sequence[last] > sequence[r - 1]; ++last);
return last == r - 1 && SquenceOfBST(sequence, l, mid) && SquenceOfBST(sequence, mid, r - 1);
}
};

Java

public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if (null == sequence || sequence.length == 0) {
System.out.println("数组为null");
return false;
}
int n = sequence.length;
return verify(sequence, 0, n-1);
}

private boolean verify(int [] sequence, int start, int stop) {//最开始的start表示索引0，stop表示索引为n-1
if (start >= stop) {
return true;
}
int root = sequence[stop];//拿到根节点
int i = start;
for (;i<stop;i++) {//一直到当前的根节点
if (root < sequence[i]) {//当找到大于root节点的元素时跳出来
break;
}
}
int j = i;//之所以换一个变量，是为了保存 i此时所在的位置，方便之后针对左右子树分别处理
for (;j<stop;j++) {
if (root > sequence[j]) {//如果二叉搜索树的右子树中有比root节点小的节点，则证明不对
return false;
}
}
return verify(sequence, start, i-1) && verify(sequence, i, stop-1);
}
}

python

class Solution:
def VerifySquenceOfBST(self, sequence):
if sequence == []:
return False
if len(sequence) == 1 or len(sequence) == 2:
return True
else:
root = sequence.pop(-1)
sign = 0
note = 0
flag = 0
for i in range(len(sequence)):
if sign is 0 and sequence[i] > root:
note = i
sign = -1
if sequence[i] > root:
sign = 1
flag += 1
if (sign == 1) and (sequence[i] < root):
return False
if sign is 0:
note = i
if flag == len(sequence):
note = 1
return self.VerifySquenceOfBST(sequence[:note]) and self.VerifySquenceOfBST(sequence[note:])


©️2019 CSDN 皮肤主题: 技术工厂 设计师: CSDN官方博客