翻转二叉树c语言实现
时间: 2024-05-10 08:12:21 浏览: 120
翻转二叉树是一种常见的二叉树操作,其实现方式如下:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* invertTree(struct TreeNode* root) {
if (!root) return NULL; // 如果根节点为空,直接返回NULL
// 递归调用翻转左右子树
struct TreeNode* temp = root->left;
root->left = invertTree(root->right);
root->right = invertTree(temp);
return root; // 返回根节点
}
int main() {
// 构造一个二叉树,以1为根节点,2和3为左右子节点
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->right->left = NULL;
root->right->right = NULL;
// 翻转二叉树
struct TreeNode* invertedRoot = invertTree(root);
// 输出翻转后的二叉树
printf("%d\n", invertedRoot->val); // 输出1
printf("%d\n", invertedRoot->left->val); // 输出3
printf("%d\n", invertedRoot->right->val); // 输出2
return 0;
}
```
阅读全文