二进制树C
Binary Tree C++
本文关键字:二进制 更新时间:2023-10-16
所以,我一直在研究一个二进制树程序,我很难创建打印方法(void)来打印树中的所有字段。任何帮助和建议都会很棒!我有一个添加方法,可以将数据点添加到数组中的计数位置,然后增加计数。
#include <iostream>
#include<iomanip>
using namespace std;
class bin_tree_node
{
private:
int myArray[100];
int count;
public:
bin_tree_node()
{
count = 0;
}
void add(int num)
{
myArray[count] = num;
count++;
};
int returnFirstItemInArray()
{
return myArray[0];
}
void preorder(int i)
{
cout << myArray[i] << endl;
int leftChildIndex = 2 * i + 1;
int rightChildIndex = 2 * i + 2;
if (leftChildIndex < count)
{
preorder(leftChildIndex);
if (rightChildIndex < count)
preorder(rightChildIndex);
}
}
};
int main()
{
bin_tree_node *myBinTreePtr = new bin_tree_node();
int inputNum;
do
{
cout << "Enter a number into the tree, enter -1 to quit: ";
cin >> inputNum;
if (inputNum == -1)
{
break;
}
myBinTreePtr->add(inputNum);
} while (inputNum != -1);
myBinTreePtr->preorder(0);
return 0;
}
我很难创建打印方法(void)以打印所有 树上的田地。
我发现并改编了以下内容(我认为来自rosettacode.org/wiki/avl_tree)。从那以后一直是我最喜欢的。
void showNodeAtLvl(int lvl) {
std::cout << std::setw(lvl) << m_key << std::endl; }
template <class T>
void BBT::AVLtree<T>::showTallTree(AVLnode<T>* n, int lvl)
{
if (nullptr != n)
{
showTallTree(n->m_left, lvl+1);
n->showNodeAtLvl(7*lvl);
showTallTree(n->m_right, lvl+1);
}
}
我的片段使用指针左右节点,您需要用阵列索引方案替换指针(当您弄清楚时)
测试和输出示例:
Inserting values 11 to 41
tree.showTallTree:
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
注意 - 示例的中间和树的根为26,左侧为26。树叶在右边。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 有根的二进制搜索树.保留与其父级的链接
- 多态二进制函数
- 正在读取二进制文件(is_open)
- visual在c++中将十进制数转换为二进制数
- C++十进制到二进制,如何转换
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 二进制搜索树叶数问题
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为什么二进制搜索在我的测试中不起作用
- 重载==不适用于二进制树
- 正在尝试重载二进制搜索树分配运算符
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 带有数组键C++的二进制映射
- 如何将二进制格式的 C++ 对象的 std::vector 保存到磁盘?
- 二进制数之和(使用C样式字符串)
- 如何从dicom文件中读取二进制数据
- 基于编译器选项的编译二进制路径