数据结构:
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 class IteratorNodeTool {
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);//打印路径
} else {
Iterator it = childlist.iterator();
while (it.hasNext()) {
node child = (node) it.next();
iteratorNode(child, pathstack);//深度优先 进入递归
pathstack.pop();//回溯时候出栈
}
}
}
public static void main(String[] args) {
List<node> roots = node.getInitNode();
IteratorNodeTool tool = new IteratorNodeTool();
for (node n : roots) {
Stack<node> pathstack = new Stack();
tool.iteratorNode(n, pathstack);
}
}
}
输出结果: