输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6,5]
输出: true
提示:
数组长度 <= 1000
代码:
class Solution {
public boolean verifyPostorder(int[] postorder) {
if(postorder.length==0)
{
return true;
}
return find(postorder,0,postorder.length-1);
}
public boolean find(int[] postorder,int start,int end)
{
if(start>=end)
{
return true;
}
int i = start,j = end-1;
while(i<end&&postorder[i]<postorder[end])
{
i++;
}
while(j>start&&postorder[j]>postorder[end])
{
j--;
}
if(i<j)
{
return false;
}
return find(postorder,start,i-1)&&find(postorder,j+1,end-1);
}
}