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

题目:

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

分析:

递归程序设计比较简单

    访问一个节点,只要不为空则交换左右孩子,然后分别对左右子树递归。

非递归实质是需要我们手动完成压栈,思想是一致的


代码如下(GCC编译通过):

#include "stdio.h"
#include "stdlib.h"

#define MAXSIZE 8

typedef struct node
{
	int data;
	struct node * left;
	struct node * right;
}BTree;

void swap(BTree ** x,BTree ** y);//交换左右孩子
void mirror(BTree * root);//递归实现函数声明
void mirrorIteratively(BTree * root);//非递归实现函数声明
BTree * CreatTree(int a[],int n);//创建二叉树(产生二叉排序树)
void Iorder(BTree * root);//中序遍历查看结果

int main(void)
{
	int array[MAXSIZE] = {5,3,8,7,2,4,1,9};
	BTree * root;

	root = CreatTree(array,MAXSIZE);

	printf("变换前:\n");
	Iorder(root);

	printf("\n变换后:\n");//两次变换,与变化前一致
	mirror(root);
	mirrorIteratively(root);
	Iorder(root);



	printf("\n");

	return 0;
}

void swap(BTree ** x,BTree ** y)
{
	BTree * t = * x;
	* x = * y;
	* y = t;
}

void mirror(BTree * root)
{
	if(root == NULL)//结束条件
		return;
	
	swap(&(root->left),&(root->right));//交换
	mirror(root->left);//左子树递归
	mirror(root->right);//右子树递归
}

void mirrorIteratively(BTree * root)
{
	int top = 0;
	BTree * t;
	BTree * stack[MAXSIZE+1];
	
	if(root == NULL)
		return;

	//手动压栈、弹栈
	stack[top++] = root;
	while(top != 0)
	{
		t = stack[--top];		
		swap(&(t->left),&(t->right));

		if(t->left != NULL)
			stack[top++] = t->left;
		if(t->right != NULL)
			stack[top++] = t->right;
	}
}

//产生二叉排序树
BTree * CreatTree(int a[],int n)
{
	BTree * root ,*p,*cu,*pa;
	int i;
	
	root = (BTree *)malloc(sizeof(BTree));
	root->data = a[0]; 
	root->left = root->right =NULL;

	for(i=1;i<n;i++)
	{
		p = (BTree *)malloc(sizeof(BTree));
		p->data = a[i];
		p->left = p->right =NULL;
		cu = root;

		while(cu)
		{
			pa = cu;
			if(cu->data > p->data)
				cu = cu->left;
			else
				cu = cu->right;
		}
		if(pa->data > p->data)
			pa->left = p;
		else
			pa->right = p;
	}	

	return root;
}
//中序遍历
void Iorder(BTree * root)
{
	if(root)
	{		
		Iorder(root->left);
		printf("%3d",root->data);
		Iorder(root->right);
	}
}



转载于:https://my.oschina.net/u/1470003/blog/226304

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值