使用c语言用递归的方式统计二叉树的结点个数同时交换二叉树每个结点的左孩子和右孩子
时间: 2023-11-14 22:06:16 浏览: 48
可以使用以下的C语言代码来实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结点结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 创建新结点的函数
TreeNode* NewNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
// 统计二叉树结点个数的递归函数
int CountNodes(TreeNode* root) {
if (root == NULL) {
return 0;
}
return CountNodes(root->left) + CountNodes(root->right) + 1;
}
// 交换二叉树每个结点的左右孩子的递归函数
void SwapChildren(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
SwapChildren(root->left);
SwapChildren(root->right);
}
int main() {
// 创建二叉树
TreeNode* root = NewNode(1);
root->left = NewNode(2);
root->right = NewNode(3);
root->left->left = NewNode(4);
root->left->right = NewNode(5);
root->right->left = NewNode(6);
root->right->right = NewNode(7);
// 统计二叉树结点个数并输出
int count = CountNodes(root);
printf("Number of nodes: %d\n", count);
// 交换二叉树每个结点的左右孩子并输出
SwapChildren(root);
printf("After swapping:\n");
printf("Left child of root: %d\n", root->left->val);
printf("Right child of root: %d\n", root->right->val);
printf("Left child of left child of root: %d\n", root->left->left->val);
printf("Right child of left child of root: %d\n", root->left->right->val);
printf("Left child of right child of root: %d\n", root->right->left->val);
printf("Right child of right child of root: %d\n", root->right->right->val);
return 0;
}
```
运行结果如下:
```
Number of nodes: 7
After swapping:
Left child of root: 3
Right child of root: 2
Left child of left child of root: 7
Right child of left child of root: 6
Left child of right child of root: 5
Right child of right child of root: 4
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)