本文主要是介绍递归树结构,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
查找全部节点:
查找具体节点的子节点,孙子节点:
上面的图是用java递归树结构运行的效果,和预测的结果相同。接下来是代码实现:
import java.util.*;
public class LookWord {private ArrayList<TreeBean> treeList = new ArrayList<TreeBean>(); //初始public static void main(String[] args) {LookWord lw = new LookWord();lw.init(); // 初始化数据//lw.findAll(lw.treeList); //查找指定的集合lw.findWho("11",lw.treeList); //找到指定的id 的集合}// 查找id的父节点public void findWho(String id,ArrayList<TreeBean> ts) {for (TreeBean t : ts) {if(t.getId().equals(id)&&t.getChildren()!=null){ //找到了那个对象就不断查找出来findAll(t.getChildren());}else{if(t.getChildren()!=null){findWho(id,t.getChildren());}}}}// 根据查找的集合查找public void findAll(ArrayList<TreeBean> findList) {// 根据集合的大小找子集合作为查找集合的目标for (int i = 0; i < findList.size(); i++) {TreeBean tb = findList.get(i);System.out.println(tb.toString()); // 不管有没有子节点都要进行输出if (tb.getChildren() != null) { // 如果有子节点则继续输出findAll(tb.getChildren()); // 如果子节点不为空则继续查找}}}// 初始化private void init() {ArrayList<TreeBean> children111 = new ArrayList<TreeBean>();TreeBean tb111 = new TreeBean("1111", "one1111", "111");TreeBean tb112 = new TreeBean("1112", "one1112", "111");children111.add(tb111);children111.add(tb112);TreeBean tb11 = new TreeBean("111", "one111", "11");tb11.setChildren(children111);TreeBean tb12 = new TreeBean("112", "one112", "11");TreeBean tb13 = new TreeBean("113", "one113", "11");ArrayList<TreeBean> children11 = new ArrayList<TreeBean>();children11.add(tb11);children11.add(tb12);children11.add(tb13);// 为11 设置子节点TreeBean tp11 = new TreeBean("11", "one1", "1");tp11.setChildren(children11);TreeBean tp12 = new TreeBean("12", "one2", "1");ArrayList<TreeBean> children1 = new ArrayList<TreeBean>();children1.add(tp11);children1.add(tp12);// 为1设置12,11子节点TreeBean tb1 = new TreeBean("1", "one", "0");tb1.setChildren(children1);ArrayList<TreeBean> children2 = new ArrayList<TreeBean>();children2.add(new TreeBean("21", "two1", "2"));children2.add(new TreeBean("22", "two2", "2"));// 为2设置子节点TreeBean tb2 = new TreeBean("2", "two", "0");tb2.setChildren(children2);treeList.add(tb1);treeList.add(tb2);}
}
这篇关于递归树结构的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!