剑指 Offer 33. 二叉搜索树的后序遍历序列
作者:互联网
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
递归
class Solution {
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++;
}
return p == j && recur(postorder, i, m - 1) && recur(postorder, m, j - 1);
}
}
单调栈
import java.util.Stack;
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;
}
while (!stack.isEmpty() && stack.peek() > postorder[i]) {
root = stack.pop();
}
stack.add(postorder[i]);
}
return true;
}
}
标签:return,recur,Offer,33,二叉,int,Stack,stack,postorder 来源: https://www.cnblogs.com/tianyiya/p/15812540.html