数据结构:
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);
}
}
}
输出结果:

该博客主要讨论了数据结构中的节点类定义,包括文本属性和子节点列表。然后展示了如何使用深度优先搜索遍历节点并打印路径。测试代码演示了从根节点开始的遍历过程,输出了所有可能的路径。
1173

被折叠的 条评论
为什么被折叠?



