【发布时间】:2018-10-16 11:36:13
【问题描述】:
我的任务是在向量中存储二叉树。在每个节点中存储一个 int ID、int Age 和一个字符串名称。
节点按 ID 在向量中存储和组织。
在向量中存储二叉树时,我使用算法 2i 和 2i+1 分别指示节点的左子节点和右子节点。
我已经设法创建了一个我认为满足这些条件的插入方法,但是由于某种原因,在尝试打印我的向量的值时,我似乎得到了负值。对于这个特定示例,我插入以下值
100 21 斯坦
50 30 菲尔
我尝试放置另一个节点
30 31 爱丽丝
根据消息来源,这会导致树变得不平衡。
所以我尝试使用存储在向量中的节点创建平衡的二叉搜索树。以前我使用这个先前的插入结构创建了一个不平衡树。但是,我并不完全理解什么是平衡二叉搜索树
所以我的问题如下:
究竟什么是平衡二叉搜索树?
您建议我在插入函数中进行哪些更改以鼓励创建平衡树?
提前致谢!
这是我的代码:
#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