2014-06-16 179 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