java 遍曆樹結點 同時保留所有從根到葉子結點的路徑

來源:互聯網
上載者:User

標籤: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 遍曆樹結點 同時保留所有從根到葉子結點的路徑

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.