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

题目:输入一棵二元查找树,将该树转换为它的镜像,即在转换后的二元查找树中,左子树的结点都大于右子树的结点。

要求:用递归和循环两种方法完成树的镜像转换。

举例:

        8                     8
      /   \       转换       /   \
     6     10     -->      10    6
    /  \   / \            /  \   / \
   5    7 9   11         11   9 7   5
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <stack>
using namespace std;

typedef struct node
{
	int key;
	struct node *pleft;
	struct node *pright; 
}Node;

int CreateTreeByInsertData(Node **p,int k)//理解为什么用二级指针
{
	if(*p==NULL)      
	{
		*p=(Node *)malloc(sizeof(Node));	
		(*p)->key=k; 
		(*p)->pleft=(*p)->pright=NULL;     
		return 1;
	}
	else if(k == (*p)->key)          
		return 0;
	else if(k < (*p)->key)           
		return CreateTreeByInsertData(&(*p)->pleft,k); 
	else
		return CreateTreeByInsertData(&(*p)->pright,k);  

}

void swap(Node **l, Node **r)
{
	Node *p = *l;
	*l = *r;
	*r = p;
}

void mirror(Node *root)//递归来使得镜像对称
{
	if(root == NULL)
		return;
	swap( &(root->pleft), &(root->pright));
	mirror(root->pleft);
	mirror(root->pright);
}

void mirrorByStack(Node *root)//用栈来做得镜像对称
{
	stack<Node *>myStack;
	if(root == NULL)
		return;
	myStack.push(root);
	while(!myStack.empty())
	{
		Node *p = myStack.top();//取得栈顶元素
		myStack.pop();//只是弹出,删除,并不能取到栈顶元素
		swap( &(p->pleft), &(p->pright));
		if(p->pleft!=NULL)
			myStack.push(p->pleft);
		if(p->pright!=NULL)
			myStack.push(p->pright);
	}
}
void visitByLevel(Node *p)//层次遍历,上到下,左到右
{
	queue<Node*> myQueue;
	if(p == NULL)
		return;
	myQueue.push(p);
	while(!myQueue.empty())
	{
		Node *now = myQueue.front();
		myQueue.pop();
		printf("%d ",now->key);
		if(now->pleft) myQueue.push(now->pleft);
		if(now->pright) myQueue.push(now->pright);
	}
	printf("\n");
}


void ClearTree(Node** tree)//删除树的操作,在本题中不一定用的到
{
	if(*tree==NULL)return;
	ClearTree(&(*tree)->pleft);
	ClearTree(&(*tree)->pright);
	free(*tree);
	*tree=NULL;
}


int main()
{
	int i;
	Node *proot = NULL;
	
	int data[] = {8,6,10,5,7,9,11};

	//依次插入一些数据,创建一个二叉排序树
	for(i=0; i<sizeof(data)/sizeof(int); i++)
		CreateTreeByInsertData(&proot, data[i]);
	visitByLevel(proot);//8 6 10 5 7 9 11
	mirror(proot);
	visitByLevel(proot);//8 10 6 11 9 7 5
	mirrorByStack(proot);
	visitByLevel(proot);//8 6 10 5 7 9 11
	ClearTree(&proot);
	return 0; 
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值