本文主要介绍《二叉树递归实现交换左右子树》,没有熟练掌握二叉树的基本操作的小伙伴,戳我了解二叉树的基本操作(创建、遍历、节点个数、叶节点个数、深度)。
文章内容基于下图二叉树实现:
递归实现二叉树交换子树:
// 递归交换
void swap(BiTree root) {
if(root == NULL) return ;
// 自下而上进行交换
swap(root->lchild);
swap(root->rchild);
// 用临时节点交换左右子树
BiTNode *temp = root->rchild;
root->rchild = root->lchild;
root->lchild = temp;
return ;
}
完整代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct BiTNode{
int data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
void createBiTree(BiTree &root) {
BiTNode *p,*q;
int x;
scanf("%d",&x);
if(x == -1) return ;
p = (BiTNode *)malloc(sizeof(BiTNode));
p->data = x;
p->lchild = NULL;
p->rchild = NULL;
root = p;
createBiTree(root->lchild);
createBiTree(root->rchild);
return ;
}
void preOrder(BiTree root) {
if(root == NULL) return ;
printf("%d ",root->data );
preOrder(root->lchild);
preOrder(root->rchild);
return ;
}
// 递归交换
void swap(BiTree root) {
if(root == NULL) return ;
// 自下而上进行交换
swap(root->lchild);
swap(root->rchild);
// 用临时节点交换左右子树
BiTNode *temp = root->rchild;
root->rchild = root->lchild;
root->lchild = temp;
return ;
}
int main() {
BiTree tree;
createBiTree(tree);
printf("交换左右子树前的先序序列:");
preOrder(tree);
printf("\n");
swap(tree);
printf("交换左右子树后的先序序列:");
preOrder(tree);
return 0;
}
测试样例:
/*
8
7
6
-1
2
-1
-1
1
-1
-1
10
-1
9
5
-1
-1
4
-1
-1
*/