我很难完成这个算法来找到具有多个子节点(非二元)的树的高度。
有人知道哪里出了问题吗?
private int getHeight(Node<T> root, int height, int result){
if (root.getChildren().size()==0) {
return height;
}
height++;
//Iterate every child
for (Node<T> childNode : root.getChildren()) {
//Get the height again
height =getHeight(childNode, height, result);
//Update if new high result
if (height>result) {
result = height;
}
height = 0;
}
//Return highest point
return result;
}
最佳答案
添加高度和结果参数会使事情变得更加困难。
在函数中,找到每个 child 的高度。保留最大的。返回 1 + 最大的高度。
像这样的东西(未经测试,未编译):
private int getHeight(Node<T> root){
int max = 0;
for (Node<T> childNode : root.getChildren()) {
int height = getHeight(childNode);
if (height > max)
max = height;
}
return max + 1;
}
关于java - 获取具有多个 child 的树的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18797547/