輸入一顆二元查找樹,將該樹轉換爲它的鏡像

題目:

    輸入一顆二元查找樹,將該樹轉換爲它的鏡像,即在轉換後的二元查找樹中,左子樹的結點都大於右子樹的結點。
用遞歸和循環兩種方法完成樹的鏡像轉換。
例如輸入:
8
/ \
6 10
/\ /\
5 7 9 11
輸出:
        8
    /         \
    10         6
    /\             /\
11     9     7     5node

分析:

遞歸程序設計比較簡單函數

    訪問一個節點,只要不爲空則交換左右孩子,而後分別對左右子樹遞歸。
spa

非遞歸實質是須要咱們手動完成壓棧,思想是一致的設計


代碼以下(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);
	}
}
相關文章
相關標籤/搜索