二叉树的创建与初始化
时间: 2023-12-18 15:03:32 浏览: 38
二叉树的创建与初始化过程如下:
1. 定义二叉树结构体,包含一个指向左子树和右子树的指针和一个存储数据的变量。
```C++
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
```
2. 创建一个空树,即根节点为空指针。
```C++
TreeNode* root = nullptr;
```
3. 插入节点。二叉树的插入操作有两种方法,一种是按照顺序插入,另一种是按照值的大小插入。
按照顺序插入:
```C++
void insert(TreeNode*& root, int val) {
if (root == nullptr) {
root = new TreeNode(val);
return;
}
if (val < root->val) {
insert(root->left, val);
} else {
insert(root->right, val);
}
}
```
按照值的大小插入:
```C++
void insert(TreeNode*& root, int val) {
TreeNode* node = new TreeNode(val);
if (root == nullptr) {
root = node;
return;
}
TreeNode* cur = root;
TreeNode* pre = nullptr;
while (cur != nullptr) {
pre = cur;
if (val < cur->val) {
cur = cur->left;
} else {
cur = cur->right;
}
}
if (val < pre->val) {
pre->left = node;
} else {
pre->right = node;
}
}
```
4. 初始化二叉树。
按照顺序初始化:
```C++
vector<int> nums = {1, 2, 3, 4, 5};
for (int num : nums) {
insert(root, num);
}
```
按照值的大小初始化:
```C++
vector<int> nums = {3, 1, 5, 2, 4};
for (int num : nums) {
insert(root, num);
}
```
这样就完成了二叉树的创建与初始化。