剑指offer33 二叉搜索树的后序遍历序列

题目描述

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

参考以下这颗二叉搜索树:

1
2
3
4
5
    5
/ \
2 6
/ \
1 3

示例 1:

1
2
输入: [1,6,3,2,5]
输出: false

示例 2:

1
2
输入: [1,3,2,6,5]
输出: true

提示:

  1. 数组长度 <= 1000

解题思路

方法一:栈

方法二:递归???

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
26
27
28
29
30
31
32
class Solution33 {
// 递归调用
public boolean verifyPostorder(int[] postorder) {
return recur(postorder, 0, postorder.length - 1);
}

boolean recur(int[] postorder, int i, int j) {
if (i >= j) return true;
int p = i;
while (postorder[p] < postorder[j]) p++;//左子树部分
int m = p;
while (postorder[p] > postorder[j]) p++;//右子树部分
// 正常的后序遍历 左子树|右子树|根结点,经过遍历查找左子树和右子树后p会等于j,否则该序列不为搜索二叉树的后序遍历序列
return p == j && recur(postorder, i, m - 1) && recur(postorder, m, j - 1);
}

// 迭代:单调栈
public boolean verifyPostorder2(int[] postorder) {
Stack<Integer> stack = new Stack<>();
int root = Integer.MAX_VALUE;
for (int i = postorder.length - 1; i >= 0; i--) {
if (postorder[i] > root) {
return false;
}
while (!stack.isEmpty() && stack.peek() > postorder[i]) {
root = stack.pop();
}
stack.push(postorder[i]);
}
return true;
}
}

资料

Author

John Doe

Posted on

2021-05-28

Updated on

2021-06-13

Licensed under

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

Comments

You forgot to set the shortname for Disqus. Please set it in _config.yml.