为什么我的函数不返回计数?(二叉树)
Why isn't my function returning the count? (Binary Tree)
我的程序中的所有内容都运行良好,除了它没有显示字段的计数。我尝试更改一些代码,但它似乎没有在输出中显示它。这似乎是一个简单的错误或显然是什么,但我不知道为什么它不显示它。有人可以帮忙吗?
#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;
相关文章:
- 打印二叉树中的常见元素
- 我有两棵二叉树.我想在不更改输入树的情况下深度复制两个二叉树的结果
- 二叉树中的删除
- C++打印二叉树中的所有值
- 如何修复关卡顺序遍历问题(二叉树)的无限循环错误
- 尝试实现二叉树时的分段错误
- 二叉树搜索的实现和函数声明c++
- 找到最大路径总和,我们可以在二叉树中的任何节点开始和结束
- 二叉树中的运算符重载
- 尝试通过二叉树中的递归返回字符串(连接)
- 随机二叉树中的插入函数
- 二叉树中的最小路径和
- 为伪二叉树中的每个子级设置同级
- 二叉树表示的有序树中节点的右子节点计数
- 需要二叉树程序的帮助(不是二叉搜索树)
- 仍然找不到二叉树中的最大数字
- 二叉树直径的路径
- 递归二叉树类的斐波那契数列
- 计数二叉树中的节点
- 二叉树c++的级序遍历