昨天乐仔在群里出了一道树结构的查找问题。根据群里各位同学的答案,写出了一个看似可行的算法。本人菜鸟一个,欢迎拍砖!
题目:有一颗树,树的每个节点只存储自身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());
}
}