[英]Binary Tree C++
So, I've been working on a Binary tree program and I am having trouble creating the print method (void) to print all the fields in the tree.因此,我一直在研究二叉树程序,但在创建打印方法 (void) 以打印树中的所有字段时遇到了问题。 Any help and advice would be great!
任何帮助和建议都会很棒! I have an add method that takes a data point, and adds it to the count position in the array then increases the count.
我有一个 add 方法,它接受一个数据点,并将其添加到数组中的计数位置,然后增加计数。
#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;
}
I am having trouble creating the print method (void) to print all the fields in the tree.
我无法创建打印方法 (void) 来打印树中的所有字段。
I found and adapted the following (I think from rosettacode.org/wiki/AVL_tree).我发现并改编了以下内容(我认为来自 rosettacode.org/wiki/AVL_tree)。 It has been my favorite ever since.
从那以后它一直是我的最爱。
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);
}
}
My snippet uses pointers to left and right nodes, and you will need to replace the pointers with your array indexing scheme (when you figure it out)我的代码段使用指向左右节点的指针,您需要用数组索引方案替换指针(当您弄清楚时)
Test and output example:测试和输出示例:
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
Note - the middle of the example and the root of the tree is value 26, on the left.注意 - 示例的中间和树的根在左侧的值为 26。 Tree leaf's are on the right.
树叶在右边。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.