如何获取二叉树代码上的叶子数量



我一直得到0作为我的二叉树上的叶子数量。我没有看到我的代码有任何问题,并希望得到一些反馈。谢谢!:)

主要

.cpp
int main()
{   
    BinaryTree <int> a;
    a.insertNode(13);
    a.insertNode(28);
    a.insertNode(8);
    a.insertNode(14);
    cout << a.numNodes() << endl;
    cout << a.numLeafNodes() << endl;
    cout << a.height() << endl;
    cout << a.getWidth() << endl;
    system("PAUSE");
}

二叉树类标头。这是我的类,具有函数。

    template<class T>
class BinaryTree
    {
private:
    struct TreeNode
    {
        T value;
        TreeNode *left;
        TreeNode *right;
    };
    TreeNode *root;
    void insert(TreeNode *&, TreeNode *&);
    int countNodes(TreeNode *&nodePtr);
    void countLeaves(TreeNode* nodePtr);
    int getTreeHeight(TreeNode* nodePtr);
    int width(TreeNode* nodePtr);
public:
    BinaryTree()
    {
        root = nullptr;
    }
    void insertNode(T);
    int numNodes();
    int numLeafNodes();
    int height();
    int getWidth();
};

我的函数用于获取叶子的数量。这是我不确定问题所在的地方。

template <class T>
int BinaryTree<T>::numLeafNodes()
{
    int leafCount = 0;
    countLeaves(root);
    return leafCount;
}
template <class T>
void BinaryTree<T>::countLeaves(TreeNode* nodePtr)
{
    if (nodePtr)
    {
        countLeaves(nodePtr->left);
        countLeaves(nodePtr->right);
        if (nodePtr->left == NULL && nodePtr->right == NULL)
        {
            int leafCount = 0;
            leafCount = leafCount + 1;
        }
    }
}
template <class T>
int BinaryTree<T>::numLeafNodes()
{
    int leafCount = 0;

这将定义一个名为 leafCount 的变量。

countLeaves(root);

这不会更改上面定义的leafCount

return leafCount;

。所以这返回 leafCount ,仍然保持值0

template <class T>
void BinaryTree<T>::countLeaves(TreeNode* nodePtr)
{
    if (nodePtr)
    {
        countLeaves(nodePtr->left);
        countLeaves(nodePtr->right);
        if (nodePtr->left == NULL && nodePtr->right == NULL)
        {
            int leafCount = 0;

这定义了另一个完全独立的变量,它也恰好被命名为 leafCount

            leafCount = leafCount + 1;

这将递增上面定义的变量。

        }

。在这里,这个leafCount超出了范围并被销毁,而不会影响其范围之外的任何内容(并且由于创建,增加或销毁此leafCount没有可观察到的影响,因此编译器可能会优化所有这些)。

您通常需要返回一个值,该值指示遇到的叶节点数。这将确定当前节点是否为叶节点,如果是,则返回 1。否则,它将返回其左右子树的叶节点数之和。

最新更新