题号:剑指 Offer 33
题目名:二叉搜索树的后序遍历序列
原题URL:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true
,否则返回 false
。假设输入的数组的任意两个数字都互不相同。
示例
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6,5]
输出: true
限制
数组长度 <= 1000
思路
1.递归,后续遍历从后往前遍历,当前结点肯定是是根节点,继续找找到比根节点小的位置,这一段的左边就是左子树,这个位置的右边就是右子树
2.扫描左子树情况,是不是完全都满足左子树的条件(右子树不用了,在找左子树的临界点的时候相当于扫描过了)
3.递归遍历左子树和右子树
解题代码
public class Solution {
public boolean verifyPostorder(int[] postorder) {
//后序遍历的顺序是左右中的顺序
//二叉搜索树,左边小于中间小于右边
//那么从后往前遍历,当前结点肯定是是根节点,继续找找到比根节点小的位置,这一段的左边就是左子树,这个位置的右边就是右子树
//递归遍历左右子树
if(postorder==null||postorder.length==0) return false;
return isTree(postorder);
}
private boolean isTree(int[] postorder) {
if(postorder.length<=1) return true;
int len = postorder.length;
//根节点的值
int root = postorder[len-1];
//找到左子树和右子树的临界点
int idx = -1;
for (int i = postorder.length - 2; i >= 0; i--) {
if(root>postorder[i]) {
idx = i;
break;
}
}
//如果没找到,说明左边全是右子树,直接返回对
// if(idx==-1) return true;
//遍历左子树,左子树必须全部小于分割点,否则不是
for (int i = idx; i >= 0; i--) {
if(postorder[i]>root) return false;
}
//递归遍历左子树和右树
return isTree(Arrays.copyOfRange(postorder,0,idx+1))&&isTree(Arrays.copyOfRange(postorder,idx+1,len-1));
}
public static void main(String[] args) {
Solution s= new Solution();
int[] nums = {1,2,5,10,6,9,4,3};
boolean b = s.verifyPostorder(nums);
System.out.println(b);
}
}