今天写这题
https://www.acwing.com/problem/content/submission/code_detail/36912299/
java
class Solution {
public boolean verifySequenceOfBST(int [] sequence) {
if (sequence == null || sequence.length == 0) {
return true;
}
return verify(sequence, 0, sequence.length - 1);
}
private boolean verify(int[] postorder, int start, int end) {
if (start >= end) {
return true;
}
int root = postorder[end];
int i = start;
// 找到第一个大于根节点的元素,这个元素之前的部分是左子树
while (i < end && postorder[i] < root) {
i++;
}
// 检查右子树中的所有元素是否都大于根节点
for (int j = i; j < end; j++) {
if (postorder[j] < root) {
return false;
}
}
// 递归检查左子树和右子树
return verify(postorder, start, i - 1) && verify(postorder, i, end - 1);
}
}
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!