用c++完成二叉树的先序创建
时间: 2024-05-14 14:16:16 浏览: 45
二叉树先序递归创建及遍历
5星 · 资源好评率100%
可以按照以下步骤来完成二叉树的先序创建:
1. 定义二叉树结构体:
```c
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
```
2. 定义一个函数来创建二叉树:
```c
struct TreeNode* createTree() {
int val;
scanf("%d", &val);
if (val == -1) { // 如果输入的值为 -1,表示该节点为空
return NULL;
}
struct TreeNode* node = (struct TreeNode*) malloc(sizeof(struct TreeNode));
node->val = val;
node->left = createTree(); // 递归创建左子树
node->right = createTree(); // 递归创建右子树
return node;
}
```
3. 在主函数中调用该函数来创建二叉树:
```c
int main() {
struct TreeNode* root = createTree();
// ...
return 0;
}
```
完整代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* createTree() {
int val;
scanf("%d", &val);
if (val == -1) {
return NULL;
}
struct TreeNode* node = (struct TreeNode*) malloc(sizeof(struct TreeNode));
node->val = val;
node->left = createTree();
node->right = createTree();
return node;
}
int main() {
struct TreeNode* root = createTree();
// ...
return 0;
}
```
阅读全文