背景
在和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;
}
标签:std,index,TreeNode,createBinaryTree,C++,vector,二叉树,nodes
From: https://www.cnblogs.com/huangshiyi/p/17792549.html