我需要創建作爲一個參數的二進制搜索樹的根節點的遞歸方法。這個遞歸方法將返回整個二叉搜索樹中節點總數的int值。計數的節點以二進制搜索樹
這是我到目前爲止有:
public class BinarySearchTree<E> extends AbstractSet<E>
{
protected Entry<E> root;
//called by the main method
public int nodes()
{
return nodes(root);
}
//nodes() will count and return the nodes in the binary search tree
private int nodes(Entry<E> current)
{
if(current.element != null)
{
if(current.left == null && current.right == null)
{
if(current.element == root.element)
return 1;
deleteEntry(current);
return 1 + nodes(current.parent);
}
else if(current.left != null && current.right == null)
return nodes(current.left);
else if(current.left == null && current.right != null)
return nodes(current.right);
else if(current.left != null && current.right != null)
return nodes(current.left) + nodes(current.right);
} else return 1;
return 0;
}
主要方法調用,像這樣的節點:
System.out.println ("\nThis section finds the number of nodes "
+ "in the tree");
System.out.println ("The BST has " + bst.nodes() + " nodes");
所以我被順序行駛,一旦我得到運行搜索到沒有孩子的節點,我會刪除當前節點並返回到父節點並繼續。我運行了上述方法的調試,並且當程序最終計數並刪除根節點左側和右側上的所有節點並嘗試返回1時,程序崩潰時發生NullPointerException()。
這是對於我的實驗室來說,這個方法必須是遞歸的。
我很失落在這一點上,沒有人知道我在做什麼錯?
標記,您應該解釋一點點添加到答案爲好。 – rghome