Java 增加每个节点';二叉树中的s值乘以1
所以我想做的练习是: 编写一个递归函数,将“根”指向的二叉树中每个节点的值递增一,然后返回修改后的树。假设节点存储整数值。(-1表示空指针) 到目前为止,我掌握的代码是:Java 增加每个节点';二叉树中的s值乘以1,java,Java,所以我想做的练习是: 编写一个递归函数,将“根”指向的二叉树中每个节点的值递增一,然后返回修改后的树。假设节点存储整数值。(-1表示空指针) 到目前为止,我掌握的代码是: public BinNode BTinc(BinNode root) { if (root.right == null && root.left == null){ root.setValue(root.value() + 1); return root; }
public BinNode BTinc(BinNode root)
{
if (root.right == null && root.left == null){
root.setValue(root.value() + 1);
return root;
}
if (root.left != null) {
root.left.setValue(root.left.value() + 1);
return BTinc(root.left);
}
if (root.right != null) {
root.right.setValue(root.right.value() + 1);
return BTinc(root.right);
}
return root;
}
到目前为止,我遇到的问题发生在传入的根为-1时,其中我得到一个空指针异常。我对这是怎么发生的有点困惑。是因为我试图访问空指针的右指针和左指针吗
其中我得到一个空指针异常。我有点搞不懂怎么做
这正在发生
不能只执行root.setValue(root.value()+1)代码>因为如果根是null
在执行root.setValue
之前,您需要检查root
是否不等于null
if (root != null && root.right == null && root.left == null){ // if both left and right nodes are null then simply return root
root.setValue(root.value() + 1);
return root;
}
然后由您为根设置适当的值 实际上,您不需要检查左侧或右侧节点是否为null,这样效率很低。“您不需要通过查看子级来决定是否进行递归调用。”只需访问根并添加值,然后让递归调用执行其余操作
public BinNode BTinc(BinNode root){
if (root != null) {
root.setValue(root.value() + 1);
BTinc (root.left());
BTinc (root.right());
}
return root;
}
你完全正确。检查根在顶部是否为null,如果为null则返回它。您不检查(root!=null){//do something}。这应该是检查的第一件事。啊,非常感谢。这听起来可能是个愚蠢的问题,但为什么我不能检查根的值是否为-1并返回它?@UnitingDust查看我的帖子。明白了!我误解了这个问题。我真的认为节点的值是-1。谢谢。如果第一个条件为false,第二个条件为redudant,因此也是最后一个返回值。我删除了代码的冗余部分,保留了相同的行为。考虑如果root==null,它将返回root。否则,它也将返回root。