java递归案例, 先假设有地区这么一个类,地区呢 有上级地区, 下级的所有地区, 有地区编码, 地区名称
public class Area{
private List<Area> childs;
private Area parent;
private String code;
private String name;
public List<Area> getChilds() {
return childs;
}
public void setChilds(List<Area> childs) {
this.childs = childs;
}
public Area getParent() {
return parent;
}
public void setParent(Area parent) {
this.parent = parent;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
下面对地区进行遍历,递归找出最末级的区域
public void treeArea(Area area){
Stack<Area> stack = new Stack<Area>();
stack.push(area);
while(!stack.isEmpty()){
Area pop = stack.pop();
// 看看还有没有下级区域
if(CollectionUtil.isNotNil(pop.getChilds())){
stack.addAll(pop.getChilds());
}else{
//如果没有下级区域,表示是最末级的
System.out.println(area.getCode());
}
}
}
下面通过一个地区查找它最上级的地区
public Area findParent(Area area){
if(area == null || area.getParent() == null){
return null;
}
Area parent = area.getParent();
while(parent.getParent() != null){
parent = parent.getParent();
}
return parent;
}