c语言代码实现二叉树的以下功能。二叉树的创建、二叉树的三种递归遍历 二叉树的复制、统汁二叉树的结点数
时间: 2023-12-01 08:40:34 浏览: 57
以下是C语言代码实现二叉树的相关功能:
1. 二叉树的创建
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode* createTree() {
int val;
scanf("%d", &val);
if (val == -1) {
return NULL;
}
TreeNode *root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = val;
root->left = createTree();
root->right = createTree();
return root;
}
```
2. 二叉树的三种递归遍历
```c
void preorder(TreeNode *root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preorder(root->left);
preorder(root->right);
}
void inorder(TreeNode *root) {
if (root == NULL) {
return;
}
inorder(root->left);
printf("%d ", root->val);
inorder(root->right);
}
void postorder(TreeNode *root) {
if (root == NULL) {
return;
}
postorder(root->left);
postorder(root->right);
printf("%d ", root->val);
}
```
3. 二叉树的复制
```c
TreeNode* copyTree(TreeNode *root) {
if (root == NULL) {
return NULL;
}
TreeNode *newRoot = (TreeNode*)malloc(sizeof(TreeNode));
newRoot->val = root->val;
newRoot->left = copyTree(root->left);
newRoot->right = copyTree(root->right);
return newRoot;
}
```
4. 统计二叉树的结点数
```c
int countNodes(TreeNode *root) {
if (root == NULL) {
return 0;
}
return 1 + countNodes(root->left) + countNodes(root->right);
}
```
阅读全文