gpt4 book ai didi

Java递归二叉树方法的空指针异常

转载 作者:行者123 更新时间:2023-12-01 16:55:37 27 4
gpt4 key购买 nike

这个方法给了我一个空指针异常,我不知道为什么会这样。递归代码有问题吗?

 public void clearAllSelections(){
//Recursively clear all the selections in the sub-tree of this node
//basis:
isSelected = false;
if(isLeaf()) return;

//recursion:
childrenRight.clearAllSelections();
childrenLeft.clearAllSelections();

}

最佳答案

您的 isLeaf() 检查不够,因为二叉树中的节点可能只有一个子节点,因此您必须添加空检查:

public void clearAllSelections(){
//Recursively clear all the selections in the sub-tree of this node
//basis:
isSelected = false;
if(isLeaf()) return;

//recursion:
if (childrenRight != null)
childrenRight.clearAllSelections();
if (childrenLeft != null)
childrenLeft.clearAllSelections();

}

关于Java递归二叉树方法的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33281797/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com