【问题标题】:Counting "sticks" (nodes with one child) in a binary search tree?在二叉搜索树中计算“棒”(有一个孩子的节点)?
【发布时间】:2014-04-24 01:26:23
【问题描述】:

所以我正在使用二叉搜索树,我遇到的一种方法是一种名为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;

}

【问题讨论】:

  • 这里的递归逻辑看起来不错。你在什么树上测试这个?
  • 虽然我很高兴下面的答案对您有所帮助,但我担心您还没有真正确定您遇到问题的根本原因。新代码有效吗?如果是这样,您能否尝试找出为什么您的原始代码没有这样我们可以看到哪里出了问题?

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


【解决方案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;
}

【讨论】:

  • 我认为这不能正常工作 - 这计算的是节点的总数,而不是“棒”的总数(只有一个孩子的节点。)
  • @templatetypedef 哦,好吧,没说对。正在更新它。
  • 虽然我同意这更简洁,但原始代码有什么问题?我觉得很好。
  • @vickes 这段代码真的能解决问题吗?因为您的代码看起来更冗长,但也应该可以用作 templatetypedef 帖子。
  • @LuiggiMendoza:我认为 OP 的代码忽略了每次对 stickCt 的递归调用都会将 num 重置为 0 的点。这就是它不正确的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-23
  • 2020-08-07
相关资源
最近更新 更多