簡體   English   中英

如何計算只有一個孩子的二叉樹中的節點數?

[英]how to count the number of nodes in a binary tree with only one child?

我已經實現了以下功能:

public int count(Node n) {
    if (n == null) {
        return 0;
    } else if (n.left == null && n.right != null) {
        return 1 + count(n.right);
    } else if (n.left != null && n.right == null) {
        return 1 + count(n.left);
    }
    return 0;
}

問題是當我用以下命令調用它時:

System.out.println(tree.count(tree.root));

它僅顯示根的值。 我究竟做錯了什么?

您的代碼似乎同時具有實例方法和靜態方法的元素,這有點令人困惑。 選擇一個,並在類似方法中保持一致。 最簡單的方法是使用按位xor ^ (如果兩個表達式之一完全true則返回true

這是一種static方法。 使用Node.countNonBranchingNodes(tree)調用:

public static int countNonBranchingNodes(Node n) {
    if (n == null) return 0;
    return (n.left != null ^ n.right != null ? 1 : 0) +
           countNonBranchingNodes(n.left) +
           countNonBranchingNodes(n.right);
}

如果要使用實例方法版本,請使用tree.countNonBranchingNodes()調用:

public int countNonBranchingNodes() {
    int count = left != null ^ right != null ? 1 : 0;
    if (left != null) count += left.countNonBranchingNodes();
    if (right != null) count += right.countNonBranchingNodes();
    return count;
}

在您的代碼中,您忘記處理左右兩個子節點,因此您的代碼應如下所示:

public int count(Node n) {
    if (n == null) {
        return 0;
    } else if (n.left == null && n.right != null) {
        return 1 + count(n.right);
    } else if (n.left != null && n.right == null) {
        return 1 + count(n.left);
    } else {
        return count(n.left) + count(n.right);
    }
}

在您的代碼中,您沒有處理節點同時具有左右兩個子節點的情況。 在那種情況下,我們必須避免對該節點進行計數,但是仍然必須繼續進行左右子樹的計數。 但是在您的解決方案中,如果節點同時擁有兩個孩子,那么您只是返回0,這是不正確的。

    public int countNodesWithExactlyOneChild(Node root){
        if(root == null) return 0;
        return (havingOneChild(root) ? 1 : 0) +
                   countNodesWithExactlyOneChild(root.left) + 
                   countNodesWithExactlyOneChild(root.right);

    }

    private boolean havingOneChild(Node node) {
        if(node != null && ((node.left == null && node.right != null) ||
            (node.left != null && node.right == null))) {
            return true;
        }
        return false;
    }

看來您的節點將有5種可能性:

“僅左”,“僅右”,“左右”,“左右都不”和“空”。

public int count(Node n) {
    // null
    if (n == null) {
        return 0;
    // right only
    } else if (n.left == null && n.right != null) {
        return 1 + count(n.right);
    // left only
    } else if (n.left != null && n.right == null) {
        return 1 + count(n.left);
    // both left and right
    } else if (n.left != null && n.right != null) {
        return count(n.left) + count(n.right);
    // neither left nor right
    } else if (n.left == null && n.right == null) {
        return 1;
    // any else missing?
    } else {
        throw new RuntimeException();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM