我有以下问题。
我需要生成树数据结构,其中每个节点都有两个子节点。我认为这将是一件非常容易的事情,而且我不确定是否只有我不明白的真正简单的东西,或者这真的很难吗?
代码开始变得冗长,我无法停止此工作。邀请的数量也应该可以通过nr_invites进行调整,但是我什至无法获得带有两个节点的二叉树。.
下面的代码将运行,直到stackOverflow错误
import java.util.ArrayList;
import java.util.List;
public class First {
public static void main(String[] args){
final int nr_invites = 2;
int maxDepth = 3;
DepthHolder dpth = new DepthHolder(maxDepth, 0);
List<User> userList = new ArrayList<>();
new User(0, nr_invites, userList, dpth);
}
}
class User {
private int id;
private int nr_invites;
User(int id, int nr_invites, List<User> userList, DepthHolder dpth) {
this.id = id;
this.nr_invites = nr_invites;
System.out.println("Generating " + id);
consumeInvites(this, userList, dpth);
}
private void consumeInvites(User user, List<User> userList, DepthHolder dpth) {
userList.add(user);
for (int i = 0; i < this.nr_invites; i++) {
System.out.println(id + " is inviting " + userList.size() + " and has invited " + ( i + 1 ) );
if ( dpth.getCurrDepth() < dpth.getMaxDepth() ) {
new User( userList.size(), nr_invites, userList, dpth );
}
}
System.out.println( "curr depth " + dpth.getCurrDepth() );
dpth.increaseDepth();
}
}
class DepthHolder {
private int maxDepth;
private int currDepth;
DepthHolder(int maxDepth, int currDepth) {
this.maxDepth = maxDepth;
this.currDepth = currDepth;
}
public int getCurrDepth() {
return currDepth;
}
public int getMaxDepth() {
return maxDepth;
}
void increaseDepth() {
if ( currDepth < maxDepth ) {
currDepth++;
}
}
}
我是从完全错误的角度尝试这个吗?
只是纯Java,不需要库或框架。我试图用谷歌搜索,但我发现的都是循环“手动”受代码限制的示例像这里https://www.javagists.com/java-tree-data-structure
Node<String> node11 = node1.addChild(new Node<String>("node 11"));
Node<String> node111 = node11.addChild(new Node<String>("node 111"));
Node<String> node112 = node11.addChild(new Node<String>("node 112"));
不允许将每个循环写成自己的行,最大深度应通过最大深度参数来更改。
输出应该像:
First user generated ...
0 invites 1
0 invites 2
1 invites 3
1 invites 4
2 invites 5
2 invites 6
3 invites 7
等。
谢谢!
据我所知,这个问题是第深度的突变。一如既往突变时,在进行突变,读取等操作时应格外小心。据我所知,永远不会使用当前代码调用dpth.increaseDepth();
。要对此进行检查,请插入System.out.println("Current depth is: " + dpth.getCurrDepth());
恰好在> for
循环。
您可能会或可能不想以其他方式处理深度。在某些方面,生成看起来有点像搜索(例如DFS),并且在执行搜索的不同点深度不同,并且不一定总是增加。