我正在为二元树上的家庭作业问题编写方法。
目标:
给定二叉树,检查树是否满足每个节点的属性,其左右子节点的值的总和等于节点的值。如果节点只有一个子节点,则该节点应具有与该子节点相同的值。叶节点自动满足属性。
我收到的错误是我的代码在所有情况下都不正确。例如,如果我有一棵树
15
/ \
5 10
当它应该是真的时,我会返回假。
到目前为止,这是我的方法,我做错了什么?
boolean BTchecksum(BinNode root) {
if (root == null || root.left() == null && root.right() == null) {return true;}
BinNode leftNode = root.left();
BinNode rightNode = root.right();
int sum = (int)(leftNode.element()) + (int)(leftNode.element());
int value = (int)(root.element());
return (sum == value) && BTchecksum(root.left()) && BTchecksum(root.right());
}
答案 0 :(得分:3)
你把总和写成:
leftNode.element()) + (int)(leftNode.element)));
应该是这样的:
leftNode.element()) + (int)(rightNode.element)));
答案 1 :(得分:0)
现在,您可能会获得空指针异常,因为您引用的子节点可能为null。这可能不是最有效的解决方案,但它会处理所有情况。
public boolean BTchecksum(BinNode root) {
if (root == null || root.right()==null && root.left()==null) {
return true;
}
if (root.right() == null) {
return (root.left().value() == root.value())
&& BTchecksum(root.left());
} else if (root.left() == null) {
return (root.right().value() == root.value())
&& BTchecksum(root.right());
} else {
return (root.value() == root.left().value() + root.right().value())
&& BTchecksum(root.left()) && BTchecksum(root.right());
}
答案 2 :(得分:0)
修订(没有NullPinterException)
public boolean BTchecksum(BinNode root)
{
if (root == null || root.left() == null && root.right() == null) {return true;}
int sum = 0;
if (root.left() != null){sum = sum + root.left().value();}
if (root.right() != null){sum = sum + root.right().value();}
return (sum == root.value()) && BTchecksum(root.left()) && BTchecksum(root.right());
}