递归其实就是一种前序遍历


import java.util.*;
class category{
String name;
int id;
int pid;
category(String name,int id,int pid){
this.name=name;
this.id=id;
this.pid=pid;
}
}
public class digui {
String res="";
public String tree(Collection co,int pid){
Iterator<category> it=co.iterator();
while(it.hasNext()){
category ct=it.next();
if(ct.pid==pid){
int id=ct.id;
res+=Integer.valueOf(id)+",";
tree(co,id);
}
}
return res;
}
public static void main(String[] args){
Collection<category> co=new ArrayList<category>();
co.add(new category("食物",1,0));
co.add(new category("植物",2,0));
co.add(new category("水果",3,1));
co.add(new category("树",4,2));
co.add(new category("苹果",5,3));
co.add(new category("松树",6,4));
co.add(new category("饮料",7,1));
co.add(new category("红苹果",8,5));
digui dg=new digui();
String ress=dg.tree(co, 0);
System.out.println(ress);


}

}
/*
*输出结果:1,3,5,8,7,2,4,6,
*/

用一颗树来表示就能看出它明显是一次前序遍历
0
1 2
3 7 4
5 6
8
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值