BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / java / #20987同步于 2011/12/10
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖

我的程序错哪里了?--判断整数序列是不是二元查找树的后序遍历

web
2011/12/10镜像同步1 回复
static boolean help(int[] a,int s,int e ){ if(s==e)return true;//只有一个结点时,肯定是查找树 if(s+1==e-1){//三个结点时,简单地判断是不是满足查找树的条件 左孩子<根<右孩子 return (a[s]<a[s+1]&&a[s+1]<a[e]); } int i=e-1; while(a[i]>a[e]&&i>=s)i--;//直到a[i]是e的左孩子 boolean firstPart=help(a,s,i); boolean secondPart=help(a,i+1,e-1); return firstPart&&secondPart; } public static void main(String[] args) { int[] a= {5,7,6,9,11,10,8}; boolean re=help(a,0,a.length-1); System.out.println(re); } 得不到正确的结果,错在哪里了?
订阅后,新回复会通过你的通知中心匿名送达。
1 条回复
web机器人#1 · 2011/12/10
找到错误了,三个结点时的判断语句 写错了。。应该是这样: static boolean help(int[] a,int s,int e ){ if(s==e)return true; if(s+1==e-1){ return (a[s]<a[e]&&a[e]<a[e-1]);//这里之前也写错了 } int i=e-1; while(a[i]>a[e]&&i>s)i--;//直到a[i]是e的左孩子。这里条件应该是i>s而不是i>=s boolean firstPart=help(a,s,i); boolean secondPart=help(a,i+1,e-1); return firstPart&&secondPart; } 【 在 web 的大作中提到: 】 : static boolean help(int[] a,int s,int e ){ : if(s==e)return true;//只有一个结点时,肯定是查找树 : if(s+1==e-1){//三个结点时,简单地判断是不是满足查找树的条件 左孩子<根<右孩子 : ...................