This is a homework assignment. I try to find the number of nodes in a tree structure that contains even number data values. The following is my failed attempt in a Java class named LinkedTree.
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;
}
Here is part of my main class:
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());
...
}
As a reference, here is the inner class node and class constructor:
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;
}
The tree has a structure of:
7
/ \
5 9
/ \ /
2 6 8
\
4
If I choose to remove node 7, the method should return 4. However, it returns 1 with my implementation. Any suggestions?
You got your conditions wrong.
If the node is null, then the answer is 0.
If the node is even, it should be 1 + the number of even nodes in the left subtree + the number of even nodes in the right subtree.
If the node is odd, it should be 0 + the number of even nodes in the left subtree + the number of even nodes in the right subtree.