2019-11-02 12:07:41 +08:00
|
|
|
|
# 33. 二叉搜索树的后序遍历序列
|
|
|
|
|
|
|
|
|
|
[NowCoder](https://www.nowcoder.com/practice/a861533d45854474ac791d90e447bafd?tpId=13&tqId=11176&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
|
|
|
|
|
|
|
|
|
## 题目描述
|
|
|
|
|
|
|
|
|
|
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。假设输入的数组的任意两个数字都互不相同。
|
|
|
|
|
|
|
|
|
|
例如,下图是后序遍历序列 1,3,2 所对应的二叉搜索树。
|
|
|
|
|
|
2019-12-06 01:04:29 +08:00
|
|
|
|
<div align="center"> <img src="pics/13454fa1-23a8-4578-9663-2b13a6af564a.jpg" width="150"/> </div><br>
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
|
|
## 解题思路
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
public boolean VerifySquenceOfBST(int[] sequence) {
|
|
|
|
|
if (sequence == null || sequence.length == 0)
|
|
|
|
|
return false;
|
|
|
|
|
return verify(sequence, 0, sequence.length - 1);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private boolean verify(int[] sequence, int first, int last) {
|
|
|
|
|
if (last - first <= 1)
|
|
|
|
|
return true;
|
|
|
|
|
int rootVal = sequence[last];
|
|
|
|
|
int cutIndex = first;
|
|
|
|
|
while (cutIndex < last && sequence[cutIndex] <= rootVal)
|
|
|
|
|
cutIndex++;
|
|
|
|
|
for (int i = cutIndex; i < last; i++)
|
|
|
|
|
if (sequence[i] < rootVal)
|
|
|
|
|
return false;
|
|
|
|
|
return verify(sequence, first, cutIndex - 1) && verify(sequence, cutIndex, last - 1);
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2019-11-02 17:33:10 +08:00
|
|
|
|
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>
|