mardi 26 juillet 2016

how to count the number of nodes in a binary tree with only one child?

I have implemented the following function:

public int count(Node n) {
    if (n == null) {
        return 0;
    } else if (n.left == null && n.right != null) {
        return 1 + count(n.right);
    } else if (n.left != null && n.right == null) {
        return 1 + count(n.left);
    }
    return 0;
}

The problem is when I called it with:

System.out.println(tree.count(tree.root));

It only prints me the value of the root. What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire