【演算法】輸入一顆二元查詢樹,將該樹轉換為它的映象

pengfoo發表於2012-10-02

題目:輸入一棵二元查詢樹,將該樹轉換為它的映象,即在轉換後的二元查詢樹中,左子樹的結點都大於右子樹的結點。

要求:用遞迴和迴圈兩種方法完成樹的映象轉換。

舉例:

        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; 
}


相關文章