日期:2023-04-23 01:56:54 来源:博客园
(相关资料图)
StackOverflowError输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回true,否则返回false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5 / \ 2 6 / \ 1 3示例 1:输入: [1,6,3,2,5]输出: false示例 2:输入: [1,3,2,6,5]输出: true提示:
数组长度 <= 1000
作者:Krahets链接:https://leetcode.cn/leetbook/read/illustration-of-algorithm/5vwxx5/来源:力扣(LeetCode)著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
使用递归分治的思路:
x,划分为左右子数组;i,在此处划分数组[start,i-1]和[i,end];x,右数组的元素均大于x。x的大小关系已经确定,只需要检查右数组和x的大小关系即可。false;否则继续执行下一步终止条件:数组为空或者只有一个元素,返回true
//数组int len=arrayname.length;//数组长度class Solution { public boolean verifyPostorder(int[] postorder) { return recur(postorder,0,postorder.length-1); } public boolean recur(int[] postorder,int start,int end){ if(end-start<=1){ return true; } else{ int root_val=postorder[end]; int i=start; for(i=start;iroot_val){ break; } } //得到i,左右数组[start,i-1],[i,end-1] //检查左右数组 int flag=0; for(int j=i;j StackOverflowError递归函数的部分为:
if(flag==0){ return recur(postorder,start,i-1)&&recur(postorder,i,end-1);}而我一开始写成了:
if(flag==0){ return recur(postorder,start,i-1)&&recur(postorder,i,end);}然后一直报错显示StackOverflowError,后来发现是右数组划分的时候,传入end就会导致后序遍历一直停留在和根节点的比较上,无法退出循环,导致栈溢出。
标签:
品牌展会
全国巡演