如何创建一棵用二叉链表存储的以root为根的二叉树?
二叉链表
1条回答 默认 最新
|__WhoAmI__| 2022-12-20 21:19关注#include <stdio.h> #include <stdlib.h> // 定义二叉树结点 typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; } TreeNode; // 创建一棵二叉树 TreeNode* createBinaryTree(int *arr, int size, int index) { TreeNode *root = NULL; // 如果当前索引不越界 if (index < size) { // 创建新结点 root = (TreeNode*)malloc(sizeof(TreeNode)); root->val = arr[index]; root->left = NULL; root->right = NULL; // 递归创建左子树 root->left = createBinaryTree(arr, size, 2 * index + 1); // 递归创建右子树 root->right = createBinaryTree(arr, size, 2 * index + 2); } return root; } int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7}; int size = sizeof(arr) / sizeof(int); // 创建二叉树 TreeNode *root = createBinaryTree(arr, size, 0); return 0; }望采纳
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报