考完软考,继续刷剑指offer
题目描述:
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6,5]
输出: true
提示:
数组长度 <= 1000
思路
二叉搜索树定义:
若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
后序遍历:LRD
明白了定义也就好写了。
给定数组的最后一个值为根节点,前面分为两部分
前部分小于根节点,后面部分大于根节点
用mid来标记第一个大于根节点的下标
扫描mid到根节点的值如果有小于根节点 的值直接返回false
递归low,mid和mid+1,height
判断左子树和右子树是否也为二叉搜索树
我的代码
class Solution {
public boolean verifyPostorder(int[] postorder) {
return f(postorder,0,postorder.length-1);
}
public boolean f(int[] postorder,int low,int height){
if(height-low==1||height==low||height<low)return true;
int temp = postorder[height];
int mid = height;
for(int i = low;i<height;i++){
if(postorder[i]>temp){
mid = i;
break;
}
}
for(int i = mid+1;i<height;i++){
if(postorder[i]<temp){
System.out.println(i);
return false;
}
}
return f(postorder,low,mid-1)&&f(postorder,mid,height-1);
}
}
大佬代码
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);
}
}