采用二叉链表存储结构,交换二叉树中每个结点的左孩子与右孩子,用c++
时间: 2023-11-13 22:05:03 浏览: 77
二叉树的左右子树交换(C++)
5星 · 资源好评率100%
好的,下面是交换二叉树中每个结点的左孩子与右孩子的C++代码实现:
```c++
#include<iostream>
using namespace std;
//定义二叉树结点
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
//交换二叉树中每个结点的左孩子与右孩子
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return NULL;
TreeNode* temp = root->left;
root->left = invertTree(root->right);
root->right = invertTree(temp);
return root;
}
//中序遍历二叉树
void inorderTraversal(TreeNode* root){
if(root == NULL) return;
inorderTraversal(root->left);
cout<<root->val<<" ";
inorderTraversal(root->right);
}
int main(){
//构建二叉树
TreeNode* root = new TreeNode(4);
root->left = new TreeNode(2);
root->right = new TreeNode(7);
root->left->left = new TreeNode(1);
root->left->right = new TreeNode(3);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(9);
//中序遍历原始二叉树
cout<<"Original tree: ";
inorderTraversal(root);
cout<<endl;
//交换二叉树中每个结点的左孩子与右孩子
root = invertTree(root);
//中序遍历交换后的二叉树
cout<<"Inverted tree: ";
inorderTraversal(root);
cout<<endl;
return 0;
}
```
运行结果:
```
Original tree: 1 2 3 4 6 7 9
Inverted tree: 9 7 6 4 3 2 1
```
希望能够帮助到你!
阅读全文