java 中的空指针异常,同时在 val 树中找不到给定范围内的值
Null pointer Exception in java while finding no of values in given range in val tree
我正在尝试打印 avl 树中给定范围内的节点值。但是当我尝试 运行 程序时,我得到 NullPointerException。我无法从之前的相同问题中得到太多帮助 topic.How 我可以更正它吗 here.Here 是我那部分的代码:
public void range(int low, int up){
if(low >up){
System.out.println("Illegal input");
}
if(this.root != null){
System.out.println(rangeS(this.root,low,up) +"");
}
}
public static int rangeS(AvlNode root,int k1 ,int k2){
int c = 0;
if(root.key >= k1 && root.key <= k2){
c = c+1;
}
if(root.key > k1 ){
rangeS(root.left,k1,k2);
}
if(root.key <k2){
rangeS(root.right,k1,k2);
}
return c;
}
由于你递归调用rangeS
,root.left
or/and root.right
可能是null
。当访问 root.key
时,这将导致 NPE
。在调用 rangeS
.
之前检查 null
和 return 0
public static int rangeS(AvlNode root,int k1 ,int k2){
if(root == null) {
return 0;
}
...
}
更新:
要计算树下的顶点数,请将 rangeS
的结果添加到您的计数器 c
,例如c += rangeS(...)
.
我正在尝试打印 avl 树中给定范围内的节点值。但是当我尝试 运行 程序时,我得到 NullPointerException。我无法从之前的相同问题中得到太多帮助 topic.How 我可以更正它吗 here.Here 是我那部分的代码:
public void range(int low, int up){
if(low >up){
System.out.println("Illegal input");
}
if(this.root != null){
System.out.println(rangeS(this.root,low,up) +"");
}
}
public static int rangeS(AvlNode root,int k1 ,int k2){
int c = 0;
if(root.key >= k1 && root.key <= k2){
c = c+1;
}
if(root.key > k1 ){
rangeS(root.left,k1,k2);
}
if(root.key <k2){
rangeS(root.right,k1,k2);
}
return c;
}
由于你递归调用rangeS
,root.left
or/and root.right
可能是null
。当访问 root.key
时,这将导致 NPE
。在调用 rangeS
.
null
和 return 0
public static int rangeS(AvlNode root,int k1 ,int k2){
if(root == null) {
return 0;
}
...
}
更新:
要计算树下的顶点数,请将 rangeS
的结果添加到您的计数器 c
,例如c += rangeS(...)
.