簡體   English   中英

在二進制搜索樹中計算“棍子”(有一個孩子的節點)?

[英]Counting “sticks” (nodes with one child) in a 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;

}

問題在於您應該返回每個節點上的搖桿計數總和,而只是返回搖桿的當前值。 您可以通過以下方式重寫方法:

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