将二叉树对称交换,即求二叉树镜像C语言
时间: 2024-05-11 08:12:59 浏览: 20
将一棵二叉树对称交换即求该二叉树的镜像。在C语言中,可以通过递归实现对二叉树的镜像操作。具体实现步骤如下:
1. 如果二叉树为空,则返回空。
2. 如果二叉树不为空,则交换左右子树。
3. 递归对左子树进行镜像操作。
4. 递归对右子树进行镜像操作。
5. 返回交换后的二叉树。
代码如下:
```
void mirror(struct TreeNode* root) {
if (root == NULL) return;
struct TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
mirror(root->left);
mirror(root->right);
}
```
相关问题
c语言二叉树的镜像并打印
以下是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 *node = (TreeNode *) malloc(sizeof(TreeNode));
node->val = val;
node->left = createTree();
node->right = createTree();
return node;
}
//二叉树镜像
TreeNode *mirrorTree(TreeNode *root) {
if (root == NULL) {
return NULL;
}
TreeNode *temp = root->left;
root->left = root->right;
root->right = temp;
mirrorTree(root->left);
mirrorTree(root->right);
return root;
}
//打印二叉树(中序遍历)
void printTree(TreeNode *root) {
if (root == NULL) {
return;
}
printTree(root->left);
printf("%d ", root->val);
printTree(root->right);
}
int main() {
printf("请输入二叉树的节点(-1代表空节点):\n");
TreeNode *root = createTree();
printf("二叉树镜像前的中序遍历:\n");
printTree(root);
printf("\n");
TreeNode *newRoot = mirrorTree(root);
printf("二叉树镜像后的中序遍历:\n");
printTree(newRoot);
printf("\n");
return 0;
}
```
代码思路:
1. 定义二叉树结构体,包括节点值和左右子节点。
2. 创建二叉树函数,通过递归实现,如果输入的节点值为-1,则返回NULL,否则继续创建左右子节点。
3. 二叉树镜像函数,通过递归实现,首先交换当前节点的左右子节点,然后分别对左右子节点进行镜像操作。
4. 打印二叉树函数,通过中序遍历实现,先打印左子树,然后打印当前节点,最后打印右子树。
5. 在主函数中,先创建二叉树,然后打印二叉树镜像前的中序遍历,接着调用二叉树镜像函数,得到镜像后的二叉树,最后打印二叉树镜像后的中序遍历。
建立二叉树后求二叉树的镜像
二叉树的镜像是指将一棵二叉树的左右子树互换得到的新二叉树。对于一棵二叉树的镜像,我们可以通过递归的方法来实现。
具体实现方法如下:
1. 首先交换根节点的左右子节点
2. 递归地对根节点的左右子树分别进行镜像操作
3. 递归终止条件:节点为null
以下是Java代码实现:
```
public TreeNode mirrorTree(TreeNode root) {
if (root == null) return null;
//交换根节点的左右子节点
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
//递归对左右子树分别进行镜像操作
mirrorTree(root.left);
mirrorTree(root.right);
return root;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)