题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
思路:
本题的考点是递归,由于数组表示的是二叉树的后续遍历,最后一个数字就是根节点的值。二叉搜索树的特点是,左子树节点的值 < 根节点的值 < 右子树节点的值。根据这个特点可以将数组划分成两部分,一部分是左子树,它们的值都大小于根节点,另一部分是右子树,它们的值都大于根节点。然后使用同样的方法分析左子树和右子树,是一个递归的过程。
Java 代码:
public class Solution {
public boolean VerifySquenceOfBST(int[] s) {
if(s.length == 0) return false;
return check(s, 0, s.length-1);
}
public boolean check(int[] a, int l, int r) {
if(l >= r) return true;
int x = a[r];
int r1 = l;
while(a[r1] < x) r1++;
int l1 = r1;
int i = l1;
while(i < r) {
if(a[i] < x) return false;
i++;
}
return check(a, l, r1 - 1) && check(a, l1, r - 1);
}
}
写法2:
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if (sequence.length == 0) return false;
return verify(sequence, 0, sequence.length - 1);
}
private boolean verify(int[] sequence, int start, int end) {
if (start >= end) return true;
int leftEnd = start;
while (sequence[leftEnd] < sequence[end]) leftEnd++;
for (int rightStart = leftEnd; rightStart < end; rightStart++) {
if (sequence[rightStart] < sequence[end]) {
return false;
}
}
return verify(sequence, start, leftEnd - 1) &&
verify(sequence, leftEnd, end - 1);
}
}
Python 代码:
# -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
if not sequence:
return False
return self.check(sequence, 0, len(sequence) - 1)
def check(self, sequence, left, right):
if left >= right:
return True
r = left
while sequence[r] < sequence[right]:
r += 1
i = l = r
while i < right:
if sequence[i] < sequence[right]:
return False
i += 1
return self.check(sequence, left, r - 1) and self.check(sequence, l, right - 1)
相关题目:
1、输入一个整数数组,判断该数组是不是BST的前序遍历结果。