【问题标题】:C++ Creating an Balanced Binary Search Tree Using Array StructureC++ 使用数组结构创建平衡二叉搜索树
【发布时间】:2018-10-16 11:36:13
【问题描述】:

我的任务是在向量中存储二叉树。在每个节点中存储一个 int ID、int Age 和一个字符串名称。

节点按 ID 在向量中存储和组织。

在向量中存储二叉树时,我使用算法 2i 和 2i+1 分别指示节点的左子节点和右子节点。

我已经设法创建了一个我认为满足这些条件的插入方法,但是由于某种原因,在尝试打印我的向量的值时,我似乎得到了负值。对于这个特定示例,我插入以下值

100 21 斯坦

50 30 菲尔

我尝试放置另一个节点

30 31 爱丽丝

根据消息来源,这会导致树变得不平衡。

所以我尝试使用存储在向量中的节点创建平衡的二叉搜索树。以前我使用这个先前的插入结构创建了一个不平衡树。但是,我并不完全理解什么是平衡二叉搜索树

所以我的问题如下:

  1. 究竟什么是平衡二叉搜索树?

  2. 您建议我在插入函数中进行哪些更改以鼓励创建平衡树?

提前致谢!

这是我的代码:

#include "BinaryTree.h"
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
int index = 0;

struct Node
{
    int ID = -1;
    int age = -1;
    string name = "";

    Node()
    {


    }

    Node(int id, int Age, string nm)
    {
        this->ID = id;
        this->age = Age;
        this->name = nm;
    }
};

vector<Node> binaryTree;


BST::BST()
{

}





void BST::insert()
{
    unsigned int ID;
    int AGE;
    string NAME;
    int root = 0;

    bool success = false;
    cout << "Please enter the ID number, age and name:" << endl;


    cin >> ID >> AGE >> NAME;

    Node *tree = new Node(ID, AGE, NAME);



    if (!binaryTree.empty())
    {
        do
        {
            if (tree->ID > binaryTree.at(root).ID && binaryTree.at(root).ID != 0)
            {
                root = 2 * root + 2;
                if (root >= binaryTree.size()) binaryTree.resize((2 * root + 2 + 1) * 5);

            }

            if (tree->ID < binaryTree.at(root).ID && binaryTree.at(root).ID != 0)
            {
                root = 2 * root + 1;
                if (root >= binaryTree.size()) binaryTree.resize((2 * root + 2 + 1) * 5);

            }

            if (binaryTree.at(root).ID == -1)
            {
                binaryTree[root] = *tree;
                success = true;
            }
        } while (!success);
    }

    if (binaryTree.empty())
    {
        binaryTree.push_back(*tree);
    }

    delete tree;

}

【问题讨论】:

  • 关于平衡二叉树的讨论对于像 StackOverflow 这样的简单问答网站来说太大了。在网上搜索“c++ 平衡二叉树示例”或“c++ 平衡二叉树教程”。
  • 提示:二叉树和所有使用数组或向量的链表与使用指针的算法相同。不同之处在于数组版本对链接使用数组索引而不是指针。
  • 提示:首先让树作为二叉树工作。然后加入平衡。这使您可以专注于平衡问题,而不必担心二叉树问题。

标签: c++ vector data-structures binary-search-tree nodes


【解决方案1】:

我会使用heap,这是平衡二叉树的最极端形式(数组中的所有索引都必须是满的,才能使用下一个索引)。

您使用的2i2i+1 算法应该可以正常工作(请记住不要使用 0 索引)。

要插入,您可以执行以下操作:

1) 在数组中第一个未使用的索引处添加新元素。

2) 使用upheap 算法。它的工作方式是将元素与其父元素进行比较,并根据树的属性进行交换(例如,如果子元素 > 父元素,则在最大堆中)。您递归地执行此操作,直到树的根(索引 1)。这需要O(log n) 时间。

这应该会为您提供一个完美平衡的二叉树和一个数组实现。

【讨论】:

  • 请给出代码作为答案,它不是文献
  • @myworldbox nope
猜你喜欢
  • 2023-03-17
  • 1970-01-01
  • 2013-12-18
  • 1970-01-01
  • 1970-01-01
  • 2014-03-07
  • 2012-05-13
相关资源
最近更新 更多