交换二叉树的左右子树
采用递归算法实现,想要交换 t 的左右子树,首先交换 t 的左子树的左右子树,再交换 t 的右子树的左右子树,最后交换 t 的左右子树,结点为空是边界条件。总的运行情况就是先遍历到树的边缘,然后从下往上交换,直至整棵树的左右子树都被交换。
void swap(Tree& t){
if(t == NULL) return; //空结点返回上一层
swap(t->left); //实现左子树的交换
swap(t->right); //实现右子树的交换
//交换左右子树
TreeNode* p = t->left;
t->left = t->right;
t->right = p;
}
完整代码如下:
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
typedef struct node{
char val;
struct node* left;
struct node* right;
}TreeNode,*Tree;
void CreateTree(Tree& t){
char x;
cin>>x;
if(x == '#') t = NULL;
else{
t = new TreeNode;
t->val = x;
CreateTree(t->left);
CreateTree(t->right);
}
}
void swap(Tree& t){
if(t == NULL) return; //空结点返回上一层
swap(t->left); //实现左子树的交换
swap(t->right); //实现右子树的交换
//交换左右子树
TreeNode* p = t->left;
t->left = t->right;
t->right = p;
}
void levelOrder(Tree& t) {
if(t == NULL) return;
queue<TreeNode*> q;
q.push(t);
while(!q.empty()){
int n = q.size();
for(int i = 0;i<n;i++){
TreeNode* s = q.front();
cout<<s->val<<" ";
q.pop();
if(s->left) q.push(s->left);
if(s->right) q.push(s->right);
}
cout<<endl;
}
}
int main(){
Tree t;
CreateTree(t);
/*
a b d # # e # # c f # # #
*/
levelOrder(t);
cout<<"递归:"<<endl;
swap(t);
levelOrder(t);
}
运行结果: