Directly on the code, and then elaborate
Data structure Definition:
/** * */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; }}
Traversing and saving paths
/** * */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 ();// Log all paths from the root node to the leaf node private void print (List lst)//print out path {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);//into the Stack List childlist=n.getchildlist (); if (childlist==null)//No Child description is leaf node {List lst=new ArrayList (); Iterator Stackit=pathstack.iterator (); while (Stackit.hasnext ()) {Lst.add (Stackit.next ()); } print (LST);//printing Path Pathmap.put (N.gettext (), LST);//save path information return; }else {Iterator it=childlist.iterator (); while (It.hasnext ()) {node child= (node) it.next (); Iteratornode (child,pathstack);//depth first enters recursive pathstack.pop ();//Backtracking timeOut stack}}}public static void Main (string[] args) {stack <node>pathstack=new stack (); node N=node.getinitnode (); Ite Ratornodetool tool=new Iteratornodetool (); Tool.iteratornode (n, Pathstack);}}
Java Traversal tree node preserves all paths from root to leaf nodes at the same time