標籤:blog ar java 資料 2014 log 代碼 ad new
直接上代碼,以後再細說
資料結構定義:
/** * */package Servlet;import java.util.ArrayList;import java.util.List;/** * @author lei * */public class node {private String text;private List<node>childList;public String getText() {return text;}public void setText(String text) {this.text = text;}public List<node> getChildList() {return childList;}public void setChildList(List<node> childList) {this.childList = childList;}public static node getInitNode(){node nodeA=new node();nodeA.setText("A"); node nodeB=new node(); nodeB.setText("B"); node nodeC=new node(); nodeC.setText("C"); node nodeD=new node(); nodeD.setText("D"); node nodeE=new node(); nodeE.setText("E"); List<node>lstB=new ArrayList(); lstB.add(nodeC); lstB.add(nodeD); nodeB.setChildList(lstB); List<node>lstA=new ArrayList(); lstA.add(nodeB); lstA.add(nodeE); nodeA.setChildList(lstA); return nodeA; }}
遍曆並儲存路徑
/** * */package Servlet;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Stack; /** * @author lei * */public class IteratorNodeTool {Map<String,List> pathMap=new HashMap();//記錄所有從根節點到葉子結點的路徑private void print(List lst)//列印出路徑{Iterator it=lst.iterator();while(it.hasNext()){node n=(node)it.next();System.out.print(n.getText()+"-");}System.out.println();}public void iteratorNode(node n,Stack<node> pathstack){ pathstack.push(n);//入棧 List childlist=n.getChildList(); if(childlist==null)//沒有孩子 說明是葉子結點 { List lst=new ArrayList(); Iterator stackIt=pathstack.iterator(); while(stackIt.hasNext()) { lst.add(stackIt.next()); } print(lst);//列印路徑 pathMap.put(n.getText(), lst);//儲存路徑資訊 return; }else { Iterator it=childlist.iterator(); while(it.hasNext()) { node child=(node)it.next(); iteratorNode(child,pathstack);//深度優先 進入遞迴 pathstack.pop();//回溯時候出棧 } } }public static void main(String[] args) {Stack <node>pathstack=new Stack();node n=node.getInitNode();IteratorNodeTool tool=new IteratorNodeTool();tool.iteratorNode(n, pathstack);}}
java 遍曆樹結點 同時保留所有從根到葉子結點的路徑