树的递归查找

    昨天乐仔在群里出了一道树结构的查找问题。根据群里各位同学的答案,写出了一个看似可行的算法。本人菜鸟一个,欢迎拍砖!   

 

题目:有一颗树,树的每个节点只存储自身id和子节点id集合。问给出任意一个节点,求出该节点到根节点路径。

package collections;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class YlTree {

 public static Map<String,Node> map = new HashMap();
 List result = new ArrayList();
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Node a = createTree();
  
  List path = new ArrayList();
  path.add(a.getNodeId());
  
  getPath(a,map.get("g"),path);
 }
 
 public static void getPath(Node root,Node target,List path){
  List<String> list = root.getNodeList();
  for (int i = 0; i < list.size(); i++) {
   //复制路径
   List path2 = new ArrayList();
   for (int j = 0; j < path.size(); j++) {
    path2.add(path.get(j));
   }
   String nodeId = list.get(i);
   path2.add(nodeId);
   if(nodeId==target.getNodeId()){
    for (int j = 0; j < path2.size(); j++) {
     System.out.println("======="+path2.get(j));
    }
   }else{
    //递归查找
    Node node = map.get(nodeId);
    getPath(node,target,path2);
   }
  }
 }
 
 public static Node createTree(){
  Node a = new Node("a");
  Node b = new Node("b");
  Node c = new Node("c");
  Node d = new Node("d");
  Node e = new Node("e");
  Node f = new Node("f");
  Node g = new Node("g");
  
  //根节点
  a.addChild(b);
  a.addChild(c);
  
  b.addChild(d);
  
  c.addChild(e);
  c.addChild(f);
  
  e.addChild(g);
  
  //放入map,利于查找
  map.put("a", a);
  map.put("b", b);
  map.put("c", c);
  map.put("d", d);
  map.put("e", e);
  map.put("f", f);
  map.put("g", g);
  
  return a;
 }

}

class Node{
 private String nodeId;
 private List<String> nodeList;
 
 public String getNodeId() {
  return nodeId;
 }
 public void setNodeId(String nodeId) {
  this.nodeId = nodeId;
 }
 public List<String> getNodeList() {
  return nodeList;
 }
 public void setNodeList(List<String> nodeList) {
  this.nodeList = nodeList;
 }
 
 Node(String nodeId){
  this.nodeId = nodeId;
  this.nodeList = new ArrayList();
 }
 
 public void addChild(Node node){
  this.nodeList.add(node.getNodeId());
 }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值