2014-06-16 113 views
0

我已经找到了高度,然后用k值我正在做postorder来打印元素,但它显示NullPointer异常作为数据不打印。在二叉树中查找K元素

Java代码:

public void kDisplay(int k) { 
    auxkDisplay(root, k); 
} 

public void auxkDisplay(TreeNode root1, int k) { 
    int l = h(root1); 
    if (l - k == 0) 
     return; 
    System.out.print(root1.data + "-"); 
    auxkDisplay(root1.left, k++); 
    auxkDisplay(root1.right, k++); 
} 

public int h(TreeNode current) { 
    TreeNode current1 = current; 
    if (current1 == null) 
     return -1; 
    int l = 1 + h(current1.left); 
    int r = 1 + h(current1.right); 
    return Math.max(l, r); 
} 

回答

1

您的问题是在这个递归,你缺少的基本情况:

public void auxkDisplay(TreeNode root1, int k) { 
    if(root1 == null) // to avoid calling null.left or null.right 
     return; 

    int l = h(root1); 
    if (l - k == 0) 
     return; 
    System.out.print(root1.data + "-"); 
    auxkDisplay(root1.left, k++); 
    auxkDisplay(root1.right, k++); 
} 

如果你打电话给左或右节点或目录root1不检查,如果当前root1不等于null,在某个特定时间,叶子将不会有任何子节点,因此传递为null的叶节点将最终调用null.left或null.right将导致NullPointerException