2012-12-02 72 views
0

這是一項家庭作業。我嘗試查找包含偶數數據值的樹結構中的節點數。以下是我在名爲LinkedTree的Java類中失敗的嘗試。查找包含偶數數據值的樹中的節點數

public int numEvenKeys() { 
     return numEvenKeysTree(root);  
} 

private static int numEvenKeysTree(Node root) { 
     int num = 0; 

     if (root == null) 
      return 0;   
     else if (root.left != null || root.right != null) 
      return num + numEvenKeysTree(root.left) 
        + numEvenKeysTree(root.right); 
     else if (root.key % 2 == 0) 
      num = 1; 

     return num; 
} 

這裏是我的主類的一部分:

public static void main(String[] args) { 
       Scanner in = new Scanner(System.in); 

       LinkedTree tree = new LinkedTree(); 
       tree.insert(7, "root node"); 
       tree.insert(9, "7's right child"); 
       tree.insert(5, "7's left child"); 
       tree.insert(2, "5's left child"); 
       tree.insert(8, "9's left child"); 
       tree.insert(6, "5's right child"); 
       tree.insert(4, "2's right child"); 
        ... 
       *** remove a node of your choice *** 
        ... 
       System.out.print("number of nodes with even keys in this tree: "); 
       System.out.println(tree.numEvenKeys()); 
        ... 
    } 

作爲參考,這裏是內部類節點和類的構造函數:

private class Node { 
    private int key;   // the key field 
    private LLList data;  // the data items associated with this key 
    private Node left;  // reference to the left child/subtree 
    private Node right;  // reference to the right child/subtree 
    private Node parent;  // reference to the parent 

    private Node(int key, Object data, Node left, Node right, Node parent){ 
     this.key = key; 
     this.data = new LLList(); 
     this.data.addItem(data, 0); 
     this.left = left; 
     this.right = right; 
     this.parent = parent; 
    } 

    private Node(int key, Object data) { 
     this(key, data, null, null, null); 
    } 
} 

// the root of the tree as a whole 
private Node root; 

public LinkedTree() { 
    root = null; 
} 

樹具有以下結構:

 7 
    /\ 
    5 9 
/\/
    2 6 8 
    \ 
    4 

如果我選擇要刪除節點7,該方法應返回4。但是,它會在我的實現中返回1。有什麼建議麼?

回答

3

你的條件錯了。

如果節點是空值,則答案爲0

如果該節點是偶數,它應該是1 +中左子樹偶數節點的數量+即使節點的右子樹的數目。

如果節點是奇數,它應該是0 +左子樹中偶數節點的數量+右子樹中偶數節點的數量。

+0

謝謝JB,它糾正了它。 – Hank