树-二叉树的创建和交换二叉树的左右子树C语音
时间: 2023-10-31 13:04:32 浏览: 89
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;
}
int main() {
printf("请输入树的节点,-1表示空节点:\n");
TreeNode* root = createTree();
return 0;
}
```
2. 交换二叉树的左右子树:
```c
void invertTree(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode* tmp = root->left;
root->left = root->right;
root->right = tmp;
invertTree(root->left);
invertTree(root->right);
}
```
阅读全文