输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6,5]
输出: true
提示:
数组长度 <= 1000
代码实现1(自己实现方法):递归
class Solution {
public static boolean verifyPostorder(int[] postorder) {
int length = postorder.length;
//递归出口
if (length <= 2) {
return true;
}
int root = postorder[length - 1];
int rightIndex = -1;
int leftIndex = -1;
//判断是否有右子树
if (postorder[length - 2] > postorder[length - 1]) {
rightIndex = length - 2;
for (int i = rightIndex; i >= 0; --i) {
if (postorder[i] < root) {
leftIndex = i;
break;
}
}
} else {
//没有右子树
leftIndex = length - 2;
}
//判断左子树是否全部数值小于root
if (leftIndex != -1) {
for (int i = leftIndex; i >= 0; --i) {
if (postorder[i] > root) {
return false;
}
}
}
//只有一个子树的情况
if (leftIndex == -1 || rightIndex == -1) {
int[] Arr = new int[length - 1];
for (int i = 0; i <= length - 2; ++i) {
Arr[i] = postorder[i];
}
return verifyPostorder(Arr);
}
//左右子树都存在的情况
int[] leftArr = new int[leftIndex + 1];
for (int i = 0; i <= leftIndex; ++i) {
leftArr[i] = postorder[i];
}
int[] rightArr = new int[rightIndex - leftIndex];
for (int i = leftIndex + 1, j = 0; i <= rightIndex; ++i, ++j) {
rightArr[j] = postorder[i];
}
return verifyPostorder(leftArr) && verifyPostorder(rightArr);
}
}
代码实现2:递归分治
大佬的代码,太牛了太牛了太牛了!!
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);
}
}
代码实现3:辅助单调栈(看懂都费劲,以后实力足够再用这个方法)
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;
}
}