多 - 树,一般来讲。而二叉树类似的。但是,它可能有叉树结构。分类似在电脑的文件夹。
static class MyTree { private Map map = new HashMap(); public void add(char parent, char child) { Listt = (List ) map.get(parent);// child list if (t == null) { t = new Vector (); map.put(parent, t); // } t.add(child); } public List getChild(char x) { return (List ) map.get(x); } } //深度优先 static void Dfs(MyTree tree,char x) { List child=tree.getChild(x); Stack stack=new Stack (); stack.push(x); while(!stack.isEmpty()) { System.out.print(stack.peek()+" "); List tmp = tree.getChild(stack.pop()); if(tmp!=null) for(int i=0;i t=tree.getChild(x); List lst=new Vector (); lst.add(x); while(lst.size()>0) { System.out.print(lst.get(0)+" "); List tmp=tree.getChild(lst.remove(0)); if(tmp!=null) { for(int j=0;j showTree(MyTree tree, char x) { List t = tree.getChild(x); // get child list List r = new Vector (); if (t == null) { r.add("" + x); return r; } for (int i = 0; i < t.size(); i++) { List ri = showTree(tree, t.get(i)); for (int j = 0; j < ri.size(); j++) { String pre = "| "; if (j == 0) { if (i == 0) pre = x + "--"; else pre = "|--"; } else { if (i == ri.size() - 1) pre = " "; else pre = "| "; } r.add(pre + ri.get(j)); } } return r; } public static void main(String[] args) { MyTree a = new MyTree(); a.add('a', 'b'); a.add('b', 'e'); a.add('b', 'f'); a.add('a', 'c'); a.add('a', 'd'); a.add('d', 'g'); a.add('d', 'i'); a.add('g', 'h'); a.add('f', 'j'); a.add('f', 'k'); List lst = showTree(a, 'a'); for (int i = 0; i < lst.size(); i++) { System.out.println(lst.get(i)); } System.out.println(); // Bfs(a, 'a'); Dfs(a, 'a'); }
版权声明:本文博主原创文章。博客,未经同意不得转载。