将二叉树的所有结点的左右子树交换

【核心代码】

//将结点的左右子树交换
void swap(BTNode* root)
{
	BTNode* tmp;
	tmp = root->lchild;
	root->lchild = root->rchild;
	root->rchild = tmp;
}

void TreeSwap(BTNode* root)
{
	if (root == NULL)//易错点:曾经想只有左右子树都为空时才返回,但是这会造成有一个空树的结点将其空子树带入循环中,导致Exception
		return;
	else
	{
		TreeSwap(root->lchild);
		TreeSwap(root->rchild);
		swap(root);
	}
}

【验证代码】

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
#define maxSize 100
typedef char ElementType;

typedef struct BTNode
{
	ElementType data;
	struct BTNode* lchild, *rchild;
}BTNode;

//由层次遍历和中序遍历序列生成二叉树的办法(自己的办法):二叉树的根节点在层次遍历序列中要先于
//其子树首先被访问,所以层次遍历序列中第一个与中序序列中匹配的字符为中序序列的根结点
BTNode* CreateBTree(ElementType level[], ElementType in[], int l1, int r1, int l2, int r2)
{
	if (l2 > r2)
	{
		return NULL;
	}
	else
	{
		BTNode* bt = (BTNode*)malloc(sizeof(BTNode));

		int i, j;//分别指向level和in中数组的元素
		int flag = 0;

		//寻找根结点,若level中第一个与in中元素匹配的即为根结点
		for (i = l1; i <= r1; ++i)
		{
			for (j = l2; j <= r2; ++j)
			{
				if (level[i] == in[j])
				{
					flag = 1;
					break;
				}
			}

			if (flag == 1)
				break;
		}

		bt->data = level[i];//曾经写错过,写成了level[j],j指向的是in中的元素,应改为in[j]
		bt->lchild = CreateBTree(level, in, l1 + 1, r1, l2, j - 1);
		bt->rchild = CreateBTree(level, in, l1 + 1, r1, j + 1, r2);

		return bt;
	}
}

void InOrder(BTNode* bt)
{
	if (bt != NULL)
	{
		InOrder(bt->lchild);
		printf("%c", bt->data);
		InOrder(bt->rchild);

	}
}

void PreOrder(BTNode* bt)
{
	if (bt != NULL)
	{
		printf("%c", bt->data);
		PreOrder(bt->lchild);
		PreOrder(bt->rchild);

	}
}

//将结点的左右子树交换
void swap(BTNode* root)
{
	BTNode* tmp;
	tmp = root->lchild;
	root->lchild = root->rchild;
	root->rchild = tmp;
}

void TreeSwap(BTNode* root)
{
	if (root == NULL)
		return;
	else
	{
		TreeSwap(root->lchild);
		TreeSwap(root->rchild);
		swap(root);
	}
}

int main()
{
	ElementType level[maxSize] = "ABCDEFGHI";
	ElementType in[maxSize] = "DHBEAIFCG";
	int len = strlen(level);

	BTNode* root = NULL;
	root = CreateBTree(level, in, 0, len - 1, 0, len - 1);

	InOrder(root);

	printf("\n");
	TreeSwap(root);
	InOrder(root);


	return 0;
}

  • 19
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值