java Kary树递归打印方法到非递归
我试图创建非递归的K元树。我发现了递归实现,并尝试更改为非递归
这是一类树:
public NaryTreeNode(String LABEL, int n) {
this.LABEL = LABEL;
this.N = n;
children = new ArrayList<>(n);
}
private void addChild(NaryTreeNode node) {
if (children.size() < N) {
children.add(node);
}
}
public void addChild(String label) {
this.addChild(new NaryTreeNode(label, N));
}
public ArrayList<NaryTreeNode> getChildren() {
return new ArrayList<>(children);
}
public NaryTreeNode getChild(int index) {
if (index < children.size()) {
return children.get(index);
}
return null;
}
public static void printTest(NaryTreeNode root) {
printUtil(root, 0);
}
private static void printUtil(NaryTreeNode node, int depth) {
for (int i = 0; i < depth; ++i) {
System.out.print(" ");
}
System.out.println(node.LABEL);
for (NaryTreeNode child : node.getChildren()) {
printUtil(child, depth + 1);
}
}
这是测试的主要方法:
public class TestNaryTree {
public static void main(String[] args) {
int n = 3;
NaryTreeNode root = new NaryTreeNode("Matter", n);
root.addChild("Pure");
root.getChild(0).addChild("Elements");
root.getChild(0).getChild(0).addChild("Metals");
root.getChild(0).getChild(0).addChild("Metalloids");
root.getChild(0).getChild(0).addChild("Non-metals");
root.getChild(0).addChild("Compounds");
root.getChild(0).getChild(1).addChild("Water");
root.getChild(0).getChild(1).addChild("Carbon dioxide");
root.getChild(0).getChild(1).addChild("Salt");
root.getChild(0).getChild(1).addChild("Camphor"); // won't add
root.addChild("Mixture");
root.getChild(1).addChild("Homogeneous");
root.getChild(1).getChild(0).addChild("Air");
root.getChild(1).getChild(0).addChild("Vinegar");
root.getChild(1).addChild("Heterogeneous");
root.getChild(1).getChild(1).addChild("Colloids");
root.getChild(1).getChild(1).addChild("Suspensions");
NaryTreeNode.printTest(root);
}
}
这是主要原因的结果:
如何将此printTest方法更改为非递归
# 1 楼答案
从代码来看,似乎需要打印预排序遍历。 如果你只是想知道如何做:使用堆栈
如果您想要一个有效的解决方案: