Question

So I am working with Binary Search Trees and one method I am having trouble with is a method called stickCt, which basically it will count the number of sticks in a tree and return the number. For it to be a stick it has to have a null and a non null child for it to be considered a stick, I have my code done and it complies but I keep getting 0 as my return value, I have no idea what is wrong I've tried moving stuff around but nothing seems to work some help would be greatly appreciated.By the way I am doing it recursively, here is the code:

// The number of nodes with exactly one non-null child
//driver

public int stickCt () {

    return stickCt(root);
}

private static int stickCt (IntNode T) {
    int num;

    //easiest case
    if (T == null) {
        num = 0;
    }
    //if the left child is null and the right child is not null
    else if (T.getLeft() == null && T.getRight() != null) {
        num = stickCt(T.getRight()) + 1;
    }
    //if right child is null and left side is not null
    else if (T.getRight() == null && T.getLeft() != null) {

        num = stickCt(T.getLeft()) + 1;
    }
    //recursive part
    else {
        num = stickCt(T.getLeft()) + stickCt(T.getRight());

    }
    return num;

}
Was it helpful?

Solution

The problem is that you should return the sum of counting the sticks on every node, but instead you just return the current value of the sticks. You could rewrite the method in this way:

private static boolean onlyOneIsNull(IntNode node1, IntNode node2) {
    return (node1 != null && node2 == null)
           || (node1 == null && node2 != null);
}

private static int stickCt(IntNode T) {
    //easiest case
    if(T==null) {
        return 0;
    }
    //evaluating if I'm a stick
    int num = 0;
    if (onlyOneIsNull(T.getLeft(), T.getRight())) {
        num = 1;
    }
    //stickCt already takes care of null nodes, no need to add a null validation for nodes
    //need to return the number of sticks from left node and right node
    return stickCt(T.getLeft()) + stickCt(T.getRight()) + num;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top