递归转化为非递归问题

suyanlong821128 2008-05-07 03:53:28
private void recursiveInsert(Element ele,ArrayList al) throws Exception{
String fatherID=(String)ele.getAttributeValue("orgID");
HashMap hm=new HashMap();
Element e=null;
for(int i=0;i<al.size();i++){
hm=(HashMap)al.get(i);
String fID=(String)hm.get("fatherID");
if(fID!=null)
{
if(fatherID.equalsIgnoreCase(fID)){
e=new Element("TreeNode");

if(hm.get("orgID")!=null){//说明是组织机构
e.setAttribute("orgID",(String)hm.get("orgID"));
e.setAttribute("ClassType","-1");
e.setAttribute("Href","seleOrgUser.do?orgID="+(String)hm.get("orgID"));
e.setAttribute("Title",(String)hm.get("orgName"));
e.setAttribute("NodeXmlSrc","lkp");
e.setAttribute("Target","right");
}
ele.addContent(e);

recursiveInsert(e,al);

}
}
} //for end
}

如何把上面的方法变成非递归的?谢谢大家了,急,没分请原谅啊 有了以后补上!
...全文
118 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
suyanlong821128 2008-05-07
  • 打赏
  • 举报
回复
楼上的好像还是递归吧--> f(i-1);
问题刚刚解决,是因为数据不太规范,本身id和父id相同,导致溢出。当时我就想到这个问题了,但是以为客户的数据这么多年了,好多人在维护,不会有什么问题,实在走投无路了,就查了下数据,果真发现问题了!

还是谢谢各位,以后多多探讨,结贴了!
老紫竹 2008-05-07
  • 打赏
  • 举报
回复
遍历有2个方法
1 深度遍历
2 广度遍历

深度等于递归

你可以去参考广度遍历的算法!
zapdos 2008-05-07
  • 打赏
  • 举报
回复
大概这样子吧

import java.util.regex.*;
public class test{
public static void f(int i){
System.out.println(i);
if(i<0)
return;
f(i-1);
}
public static void g(int i){
while(true){
System.out.println(i);
if(i<0)
break;
i--;
}
}
public static void main(String args[]){
f(5) ;
g(8);
}
}
suyanlong821128 2008-05-07
  • 打赏
  • 举报
回复
楼上能说的详细点不?
zapdos 2008-05-07
  • 打赏
  • 举报
回复
最简单就是把传入的参数移到while(true)外面,剩下的放入里面
suyanlong821128 2008-05-07
  • 打赏
  • 举报
回复
不是的,也是没办法,栈溢出了,递归太深了!
yeecheng 2008-05-07
  • 打赏
  • 举报
回复
为什么要改为非递归?用堆栈好像可以,不过会很麻烦,我想你的目的不是为了一点点效率的提升吧

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧