我目前正在将整数数组转换为具有给定顺序的树(可能是 2、3、4、5,...)。到目前为止,我只设法让它为 2 阶树工作,我正在努力实现更高阶的代码。
它的工作原理是,我们得到一组数字(例如 1 2 3 4 5 6 7 8 2),最后一个表示树的顺序。在这种情况下,2,导致这棵树:
1
/ \
2 3
/ \ / \
4 5 6 7
/
8
然后,我们必须根据提供的数字对生成的构建树进行预排序和排序后打印。因此,对于我得到的预购印刷品1 2 4 8 5 3 6 7
和我得到的后购印刷品8 4 5 2 6 7 3 1
,这两个都是正确的答案。
我用于构建树的代码是:
public static Node arrayToTree(String[] input, int order) {
Node root = createNode(input, 1, order);
return root;
}
public static Node createNode(String[] input, int i, int order) {
if(i <= input.length) {
String val = input[i-1];
if(val != null){
Node t = new Node(val);
for(int j = 0; j < order; j++) {
t.children[j] = createNode(input, order * i + j, order);
}
return t;
}
}
return null;
}
class Node {
public Node[] children = new Node[64];
public String val;
public Node(String val) {
this.val = val;
}
}
实际的问题是如何在 createNode 函数中获取正确的索引,以便节点 t 的子节点实际上是正确的。因此,例如,如果输入为 1 2 3 4 3.. 表示树的顺序为 3,因此根为 1,并且有子节点 2、3 和 4。它们位于索引 1、2 和 3 上。
public static void main(String[]args) {
String[] input = new String[]{"1", "2", "3", "4", "5", "6", "7", "8"};
int order = 2;
Node tree = arrayToTree(input, order);
System.out.print("Preorder: ");
preorder(tree);
System.out.println();
System.out.print("Postorder: ");
postorder(tree);
}
public static void preorder(Node node) {
System.out.print(node.val + " ");
for(Node n : node.children) {
if(n != null) preorder(n);
}
}
public static void postorder(Node node) {
for(Node n : node.children) {
if(n != null) postorder(n);
}
System.out.print(node.val + " ");
}
这是 postorder 和 preorder 打印的主要功能,让您了解稍后在主程序中应该如何工作。