15、输入一颗二元查找树,将该树转换为它的镜像

题目:

输入一颗二元查找树,将该树转换为它的镜像,

即在转换后的二元查找树中,左子树的结点都大于右子树的结点。
用递归和循环两种方法完成树的镜像转换。   
例如输入:
  8
  / \
  6 10
 /\ /\
5 7 9 11
输出:
  8
  / \
 10 6
 /\ /\

11 9 7 5


方法一:递归

可以用递归方法对每一个结点交换左右子树。

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include "TREE.h"

void Convert(BTNode *L);

int main()
{
	BTNode *L=NULL;
	CreateTree(&L); //建立二叉树
	printf("Before convert,the nodes in the tree are:  \n");
	OutputTree(L); //首先输出转换前的二叉树的先序遍历元素
	printf("\n");
	Convert(L);  //转换二叉树
	printf("After convert,the nodes in the tree are:  \n");
	OutputTree(L);  //输出转换后的二叉树的先序遍历元素
	printf("\n");

	return 0;
}

void Convert(BTNode *L) //递归转换当前结点的左右子树
{
	BTNode *temp=NULL;

	if (L)
	{
		temp=L->lChild; //交换左右子树
		L->lChild=L->rChild;
		L->rChild=temp;

		Convert(L->lChild);
		Convert(L->rChild);
	}
}

头文件TREE.H为建立二叉树的相关内容,如下所示:

#ifndef TREE_H
#define TREE_H

#include <stdio.h>
#include <stdlib.h>

typedef struct treeNode
{
	struct treeNode *lChild;
	struct treeNode *rChild;
	char num;
}BTNode;


void CreateTree(BTNode **L);//给出先序遍历,建立二叉树,无孩子结点用#代替。
                            //具体表述可参考http://acm.njupt.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=1019
void OutputTree(BTNode *L); //先序遍历

void CreateTree(BTNode **L)  //注意这里传的是指针的地址!!!
{
	char ch;
	ch=getchar();
	getchar();
	if (ch=='#')
	{
		(*L)=NULL;
	}
	else
	{
		*L=(BTNode*)malloc(sizeof(BTNode));
		(*L)->num=ch;
		CreateTree(&((*L)->lChild));
		CreateTree(&((*L)->rChild));
	}
}

void OutputTree(BTNode *L)
{
	if (L)
	{
		printf("%c  ",L->num);
		OutputTree(L->lChild);
		OutputTree(L->rChild);
	}
}


#endif

方法二:循环(利用BFS层次遍历每个结点,也可利用DFS)

给出代码:

#include <stdio.h>
#include <stdlib.h>
#include "TREE.h"

int front=0,rear=0;
BTNode * Queue[20];  
void Push(BTNode *s)
{
	Queue[rear++]=s;
}
void Pop()
{
	front++;
}

BTNode *GetTop()
{
	return Queue[front];
}

BTNode* Convert(BTNode *L);

int main()
{
	BTNode *L=NULL;
	CreateTree(&L);
	printf("Before convert,the nodes in the tree are:  \n");
	OutputTree(L);
	printf("\n");
	L=Convert(L);
	printf("After convert,the nodes in the tree are:  \n");
	OutputTree(L);
	printf("\n");

	return 0;
}

BTNode *Convert(BTNode *L)
{
	BTNode *temp,*cur;
	Push(L);
	while(front<rear)
	{
		cur=GetTop();  //获取栈中首元素
		if (cur->lChild!=NULL)  //若有左节点,压入队列
		{
			Push(cur->lChild);
		}
		if (cur->rChild!=NULL)  //若有右结点,压入队列
		{
			Push(cur->rChild);
		}
		temp=cur->lChild;  //交换当前结点的左右子节点
		cur->lChild=cur->rChild;
		cur->rChild=temp;
 
		Pop();  //弹出首元素
	}
	return L;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值