c++ - 递归插入二叉树(geeksforgeeks)

标签 c++ recursion tree insert binary-search-tree

我正在尝试实现 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/

相关文章:

c++ - 使用 jsoncpp 时从 JSON 中剥离私有(private)数据的最佳方法

c++ - 迭代器指向哪个索引

c++ - 测验;这会编译吗?如果是,它会返回什么(我知道答案)

java - Java 中矩阵返回错误值

java - 从 swt 树中删除边框

c++ - 如何使用 CMake 订购/设计使用更高的共享库包括

scala - 我有一个 Expr 值,在 Scala 中有两个子 Expr,我怎样才能在尾部位置执行它?

algorithm - 如何识别什么是尾递归,什么不是尾递归?

java - 如何在关系数据库中存储带有 child 的链接树?

algorithm - 用于在树中查找支配集的多项式时间算法