用c++编写算法将二叉树中所有结点的左右子树相互交换
时间: 2023-06-05 12:05:51 浏览: 145
交换二叉树中所有结点的左右子树
5星 · 资源好评率100%
很高兴回答你的问题!这是一道很经典的二叉树问题。以下是 C 语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left, *right;
};
void swapChildren(struct TreeNode* node){
if(node == NULL) return;
struct TreeNode* temp = node->left;
node->left = node->right;
node->right = temp;
swapChildren(node->left);
swapChildren(node->right);
}
int main() {
//构造一颗二叉树
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root -> val = 1;
root -> left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root -> right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root -> left -> val = 2;
root -> right -> val = 3;
root -> left -> left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root -> left -> right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root -> left -> left -> val = 4;
root -> left -> right -> val = 5;
root -> right -> left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root -> right -> right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root -> right -> left -> val = 6;
root -> right -> right -> val = 7;
//交换左右子树
swapChildren(root);
//输出交换后的结果
printf("%d\n", root -> val);
printf("%d %d\n", root -> left -> val, root -> right -> val);
printf("%d %d %d %d\n", root -> left -> left -> val, root -> left -> right -> val, root -> right -> left -> val, root -> right -> right -> val);
return 0;
}
```
该算法通过递归的方式,遍历二叉树中的每一个节点,并将其左右子树相互交换。时间复杂度为 O(n),其中 n 为二叉树中节点的个数。
阅读全文