我正在尝试实现 geeksforgeeks.com 上使用的插入功能,但在尝试将其应用于我当前的代码时遇到了一些问题。
我有一个 vector ,其中包含我需要放入二叉树的数据。我使用这个函数将数字传递给插入函数:
void populateTree(vector<string> dataVec) {
for (int i = 0; i < dataVec.size(); i++) {
insert(stoi(dataVec[i]), root);
}
}
这是插入函数:
node* insert(int x, node* node) {
if (node == nullptr)
return newNode(x);
if (x < node->data)
node->left = insert(x, node->left);
else
node->right = insert(x, node->right);
return root;
}
新节点功能:
node* newNode(int num) {
node* temp = new node;
temp->data = num;
temp->left = temp->right = nullptr;
temp->level = 1;
return temp;
}
Root 是初始化为 nullptr 的类中的私有(private)成员。我不确定我应该如何将来自 vector 的第一个节点作为根,然后递归地从那里开始插入东西。谢谢!
最佳答案
您的问题与指针的使用有关。
而不是使用 node* insert(int x, node* node)
你应该使用 node* insert(int x, node** node)
或 node* insert(int x, node*& node)
并相应地采用您的代码。
以下是更正的示例代码。 See it in execution here :
#include <iostream>
#include <vector>
using namespace std;
struct Node
{
int val;
Node* left;
Node* right;
Node(int v)
{
val = v;
left = right = nullptr;
}
};
class Tree
{
Node* root;
Tree()
{
root = nullptr;
}
public:
static void insert(int x, Node*& node)
{
if (node == nullptr)
{
node = new Node(x);
}
else
{
if (x < node->val)
insert(x, node->left);
else
insert(x, node->right);
}
}
static Tree* populateTree(vector<string> dataVec)
{
Tree* t= new Tree();
for (int i = 0; i < dataVec.size(); i++)
{
insert(stoi(dataVec[i]), t->root);
}
return t;
}
static void printTree(Node* node, string s)
{
if(node == nullptr) return;
cout<<s<< "+"<<node->val <<endl;
s += "----";
printTree(node->left,s);
printTree(node->right, s);
}
static void printTree(Tree* t)
{
if(t)
{
printTree(t->root, "");
}
}
};
int main() {
Tree* t = Tree::populateTree({"70", "2", "7", "20", "41", "28", "20", "51", "91"});
Tree::printTree(t);
return 0;
}
关于c++ - 递归插入二叉树(geeksforgeeks),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61167982/