发布于 

剑指 Offer.33-二叉搜索树的后序遍历序列

剑指 Offer.33-二叉搜索树的后序遍历序列

题目链接

<剑指 Offer 33. 二叉搜索树的后序遍历序列>

问题描述

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

官方解法(递归分治)

根据后续遍历二叉搜索树的特性,根节点的左子树全部小于根节点,右子树全部大于根节点,根据此条件,进行递归判断

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public boolean verifyPostorder(int[] postorder) {
return recur(postorder,0,postorder.length-1);
}
boolean recur(int[] postorder,int i,int j){
// 当到达单个节点的时候 直接返回true
if(i>=j) return true;
int p = i;
// 验证当前根节点左子树节点的合法性
while(postorder[p] < postorder[j]) p++;
int m = p;
// 验证当前节点右子树节点的合法性
while(postorder[p] > postorder[j]) p++;
// 当前树的合法性 当前树的左右节点序列合法,递归验证左右子树
return p == j && recur(postorder,i,m-1) && recur(postorder,m,j-1);
}
}

解法二(单调栈)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public boolean verifyPostorder(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;
// 若节点大于当前节点 则正常入栈
// 当遇到递减元素时,更新root至最接近当前节点的值
// 当前节点进栈 通过单调栈辅助验证序列合法性
while(!stack.isEmpty() && stack.peek() > postorder[i])
root = stack.pop();
stack.add(postorder[i]);
}
return true;
}
}

本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。

本站由 @John Doe 创建,使用 Stellar 作为主题。