二叉树的创建n个结点
时间: 2023-09-20 21:02:57 浏览: 64
好的,我可以为你讲解一下二叉树的创建过程。首先,我们需要定义二叉树的结构:
```
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x): val(x), left(nullptr), right(nullptr) {}
};
```
接下来,我们以递归的方式来创建二叉树。假设我们要创建n个结点的二叉树,我们可以先创建一个根结点,然后将剩余的n-1个结点分成左右两部分,分别递归创建左子树和右子树。具体代码如下:
```
TreeNode* createBinaryTree(int arr[], int start, int end) {
if (start > end) {
return nullptr;
}
int mid = (start + end) / 2;
TreeNode* root = new TreeNode(arr[mid]);
root->left = createBinaryTree(arr, start, mid - 1);
root->right = createBinaryTree(arr, mid + 1, end);
return root;
}
TreeNode* createBinaryTree(int arr[], int n) {
return createBinaryTree(arr, 0, n - 1);
}
```
这里我们假设数组arr已经按照从小到大的顺序排好,并且n为数组的长度。在createBinaryTree函数中,我们先计算出数组的中间位置mid,然后创建一个根结点,值为arr[mid]。接着,我们递归创建左子树和右子树,左子树的范围为start到mid-1,右子树的范围为mid+1到end。最后,我们返回根结点即可。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)