计数"棍棒" (二元搜索树中的节点)

时间:2014-04-23 16:57:43

标签: java algorithm data-structures binary-search-tree

所以我正在使用二进制搜索树和一个我遇到问题的方法是一个名为stickCt的方法,它基本上会计算树中的木棒数量并返回数字。因为它是一个棒,它必须有一个null和一个非null的孩子,因为它被认为是一个棒,我完成了我的代码,它符合但我一直得到0作为我的返回值,我不知道是什么问题我试过移动的东西,但似乎没有任何工作,一些帮助将非常感激。通过我递归的方式,这里是代码:

// 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;

}

1 个答案:

答案 0 :(得分:1)

问题是你应该在每个节点上返回计数棒的总和,而只是返回棒的当前值。你可以用这种方式重写方法:

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;
}