简体   繁体   English

在二进制搜索树中计算“棍子”(有一个孩子的节点)?

[英]Counting “sticks” (nodes with one child) in a binary search tree?

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. 因此,我正在使用二叉搜索树,遇到麻烦的一种方法是stickCt方法,该方法基本上将计算树中的棍子数并返回该数目。 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: 为了使其成为棍子,必须具有一个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;

}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM