【发布时间】:2018-07-13 09:38:37
【问题描述】:
我想从给定的数组和根节点构造一个图,节点如下所述,
static class TreeNode {
private int value;
private ArrayList<TreeNode> children;
public TreeNode(int nodeValue) {
this.value = nodeValue;
this.children = new ArrayList<TreeNode>();
}
public int getValue() {
return this.value;
}
public void addChild(TreeNode child) {
this.children.add(child);
}
public ArrayList<TreeNode> getChildren() {
return this.children;
}
}
下面提供的用于构造图形的数组,
T[0] = 1
T[1] = 2
T[2] = 3
T[3] = 3
T[4] = 2
T[5] = 1
T[6] = 4
数组T描述了一个城市网络,如果T[P] = Q且P≠Q,那么城市P和Q之间有一条直达路。如果2的索引是根,那么下图是,
2 - 3
/ \
1 4
/ | |
0 5 6
显然,我可以为给定的数组手动完成,
final int N = 7;
TreeNode[] nodes = new TreeNode[N];
for (int i = 0; i < N; i++) {
nodes[i] = new TreeNode(i);
}
TreeNode root = nodes[2];
root.addChild(nodes[1]);
root.addChild(nodes[3]);
root.addChild(nodes[4]);
nodes[1].addChild(nodes[0]);
nodes[1].addChild(nodes[5]);
nodes[4].addChild(nodes[6]);
当我给定一个数组和 K 值后,如何以编程方式构造?请帮忙。
【问题讨论】:
-
你试过什么?
-
@nicomp 我仍在尝试正确编写它。完成后我会在这里更新
-
@nicomp 我试过并提供了答案