二进制树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。树叶在右边。