二叉树的定义、建立、遍历函数(先中后)和释放操作函数
时间: 2024-02-23 19:03:21 浏览: 30
二叉树是一种树形结构,每个节点最多有两个子节点。常见的二叉树有二叉搜索树、满二叉树、完全二叉树等。
二叉树的定义可以用结构体表示:
```c
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
```
其中,val代表节点的值,left和right分别代表节点的左子节点和右子节点。
二叉树的建立可以采用递归的方式,例如:
```c
TreeNode* createTree() {
int val;
scanf("%d", &val);
if (val == -1) { // -1表示空节点
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = val;
root->left = createTree();
root->right = createTree();
return root;
}
```
对于二叉树的遍历,常见的有三种方式:先序遍历、中序遍历和后序遍历。以先序遍历为例:
```c
void preorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val); // 先访问根节点
preorderTraversal(root->left); // 再访问左子树
preorderTraversal(root->right); // 最后访问右子树
}
```
中序遍历和后序遍历类似,只需要修改访问根节点的位置即可。
释放二叉树的操作函数可以采用递归的方式,例如:
```c
void freeTree(TreeNode* root) {
if (root == NULL) {
return;
}
freeTree(root->left);
freeTree(root->right);
free(root);
}
```
这样就可以递归地释放二叉树的每个节点了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)