【发布时间】:2021-12-28 20:35:00
【问题描述】:
我必须编写一个程序来计算比他们的儿子大的节点而不包括叶节点,例如:
4 For this tree, the solution would be 4 because is greater than its son 3 but
\ 3 is not counted
3
这是我的方法:
//Result2 is a class that stores a T value (info of the node) and n (counter) to
// count the nodes that are bigger than it's sons, this is a method into the class of
//the node that is a generic class of binary nodes for trees (left, right and info
//parameters)
public Result2<T> countBigger()
{
Result2<T> result = new Result2<T>();
result.info = this.info;
if(this.isLeaf())
{
result.n = 0;
}
else
{
Result2<T> resultL = new Result2<T>();
Result2<T> resultR = new Result2<T>();
if(this.hasLeft())
{
resultL = this.left.countBigger();
}
else
{
resultL.info = this.info;
}
if(this.hasRight())
{
resultR = this.right.countBigger();
}
else
{
resultR.info = this.info;
}
if(result.info.compareTo(resultL.info) > 0 & result.info.compareTo(resultR.info) > 0)
{
result.n++;
}
result.n = result.n + resultL.n + resultR.n;
}
return result;
}
但我看不到错误
【问题讨论】:
-
您有什么理由分配
resultR.info = this.info;并为resultL 分配相同的值吗?如果没有左或右孩子,您不应该分配 null 或默认值吗?除非在这里遗漏了一些上下文。 -
@kks21199 如果没有子节点,我会分配实际的节点信息,因为比较不会返回节点大于其子节点,因此我不会将 1 添加到计数器,因为示例:节点父亲为 1 左侧不存在,右侧为 3,则 resultL 将是 this.info (1) 并且在比较中 3 大于他的父亲 1,因此它不添加计数器
-
@kks21199 基本上是不触发空指针,如果我不分配东西然后做比较
-
那么 result.n 呢?那包含什么?您还可以在比较之前检查对象是否为空。
-
@kks21199 result.n 正如我最初解释的那样,它是一个大于其子节点的节点的计数器,每次节点大于其子节点时,它的总和为 1
标签: java data-structures tree binary-tree nodes