C++从std::vector<int>类型数据创建二叉树

发布时间 2023-10-27 16:00:13作者: ac23

背景

在和chatGPT的日常代码交流中,这位“老师”总能给出不不少好代码,以下就是 C++从std::vector类型数据创建二叉树 的完整代码段:

TreeNode* createBinaryTree(const std::vector<int>& nodes, int index) {
    if (index >= nodes.size() || nodes[index] == -1) {
        return nullptr;
    }

    TreeNode* root = new TreeNode(nodes[index]);
    root->left = createBinaryTree(nodes, 2 * index + 1);
    root->right = createBinaryTree(nodes, 2 * index + 2);
    return root;
}

int main() {
    // Test case 1
    std::vector<int> nodes1 = {3, 9, 20, -1, -1, 15, 7};
    TreeNode* root1 = createBinaryTree(nodes1, 0);

    return 0;
}