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

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

思路

二叉搜索树的特点是 left < root < right, 其后续遍历序列的最后一个元素一定是该二叉搜索树的根节点,因此判断思路是,遍历给定序列找到第一个大于root的节点值,判断后面的其他节点是否都大于root, 若都大于的话再去递归判断两个子树的序列, 否则的话返回false;递归终止条件为left>=right

代码

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
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence == null || sequence.length == 0) return false;
int length = sequence.length;
return verify(sequence, 0, length-1);
}

public boolean verify(int [] seq, int left, int right){
if(left >= right) return true;
int root = seq[right];
int i=left;
while(i < right){
if(seq[i] > root) break;
i++;
}
int temp = seq[right];
int idx = i;
while(i < right){
if(seq[i] < temp) return false;
i++;
}
//left,i-1, i,right-1
return verify(seq, left, idx-1) || verify(seq, idx, right-1);
}
}
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!

扫一扫,分享到微信

微信分享二维码
  • © 2020 Zhang-Ke
  • Powered by Hexo Theme Ayer
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信