考研数据结构(十一):二叉树递归实现交换左右子树

本文主要介绍《二叉树递归实现交换左右子树》,没有熟练掌握二叉树的基本操作的小伙伴,戳我了解二叉树的基本操作(创建、遍历、节点个数、叶节点个数、深度)

文章内容基于下图二叉树实现:

在这里插入图片描述

递归实现二叉树交换子树:

// 递归交换
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


*/ 

在这里插入图片描述
在这里插入图片描述

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘小蓝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值