为什么我的函数不返回计数?(二叉树)

Why isn't my function returning the count? (Binary Tree)

本文关键字:二叉树 我的 函数 返回 为什么      更新时间:2023-10-16

我的程序中的所有内容都运行良好,除了它没有显示字段的计数。我尝试更改一些代码,但它似乎没有在输出中显示它。这似乎是一个简单的错误或显然是什么,但我不知道为什么它不显示它。有人可以帮忙吗?

#include <iostream>
using namespace std;
template<class T>
class BinaryTree
{
    struct Node
    {
        T data;
        Node* leftChild;
        Node* rightChild;
        Node(T dataNew)
        {
            data = dataNew;
            leftChild= NULL;
            rightChild = NULL;
        }
    };
private:
    Node* root;
    void Add(T new_Data, Node* &the_Root)
    {
        if (the_Root == NULL)
        {
            the_Root = new Node(new_Data);
            return;
        }
        if (new_Data < the_Root->data)
            Add(new_Data, the_Root->leftChild);
        else
            Add(new_Data, the_Root->rightChild);
    }
    int countTree(Node* the_Root)
    {
        if (the_Root == NULL)
            return 0;  
        else {
            int count = 1;  
            count += countTree(the_Root->leftChild);
            count += countTree(the_Root->rightChild);
            return count;  
        }
    } 
    void PrintTree(Node* the_Root)
    {
        if (the_Root != NULL)
        {
            cout << the_Root->data <<" ";
            PrintTree(the_Root->leftChild);
            PrintTree(the_Root->rightChild);
        }
    }
public:
    BinaryTree()
    {
        root = NULL;
    }
    void AddItem(T new_Data)
    {
        Add(new_Data, root);
    }
    int countTree()
    {
        return countTree(root);
    }
    void PrintTree()
    {
        PrintTree(root);
    }
};
int main()
{
    BinaryTree<int> *myBT = new BinaryTree<int>();
    myBT->AddItem(6);
    myBT->AddItem(5);
    myBT->AddItem(4);
    myBT->AddItem(18);
    myBT->AddItem(6);
    myBT->PrintTree();
    myBT->countTree();
}
不会

仅仅因为您没有编写任何代码来显示计数而显示计数。

尝试将myBT->countTree();更改为 cout << myBT->countTree(); ,您将看到打印的计数。

你实际上并没有对myBT->countTree()的结果做任何事情。尝试打印它:

std::cout << myBT->countTree() << std::endl;