求树的递归算法

BlueSoftEye 2007-06-06 06:24:36
结构 nodes 是个二维数组,结构如下:
id parentId
=================================
001 -1
002 001
003 001
004 002
005 002
006 002
007 003
008 003
树形式为:
001-->002-->004
001-->002-->005
001-->002-->006
001-->003-->007
001-->003-->008

求递归算法遍历,要求有遍历路径
...全文
261 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
jjwkl 2007-06-06
  • 打赏
  • 举报
回复
楼主,看看数据结构吧.. 尤其是树的遍历的方式那章..
BlueSoftEye 2007-06-06
  • 打赏
  • 举报
回复
自己已搞定:
/**
* 对树状结构的一维切片的层次进行递归,递归路径中...
* @param sliceColumnAndParentId String[][] 所有节点
* @param rootValue String 根节点
* @param curSliceColumn String 当前节点,第一次运行时,当前节点=根节点
* @param lastBuffer StringBuffer 递归所需的栈的缓存
* @param list List 返回结果
*/
private static void RecursionSlice(final String[][] sliceColumnAndParentId,String rootValue,String curSliceColumn,StringBuffer lastBuffer,List list) {
String[] sons = searchSonSlice(curSliceColumn, sliceColumnAndParentId);
StringBuffer sb=new StringBuffer();

if(curSliceColumn.equalsIgnoreCase(rootValue)){
lastBuffer.append(rootValue).append(";");
}

if (sons.length > 0) {
for (int i = 0; i < sons.length; i++) {
sb.setLength(0);
sb.append(lastBuffer);
curSliceColumn = sons[i];
sb.append(curSliceColumn);
sb.append(";");
RecursionSlice(sliceColumnAndParentId,rootValue,curSliceColumn,sb,list);
}
}
else {
list.add(lastBuffer.toString());
}
}
yeliming 2007-06-06
  • 打赏
  • 举报
回复
你要怎么遍历?深度优先还是广度优先?前序还是后序?

62,635

社区成员

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

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