用二叉排序樹求解逆序數

本文代碼爲自己所寫,思路參照博文:http://www.cppblog.com/myjfm/archive/2012/09/15/190772.html

#include<iostream>
using namespace std;
struct BST
{
	int value;//數
	int num_right_subtree;//右子樹中結點個數
	BST* Left;
	BST* Right;
	BST(int num)//構造函數
	{
		value=num;
		num_right_subtree=0;
		Left=NULL;
		Right=NULL;
	}
};
int Build_tree(BST *root,int num)
{
	int num_of_inversions=0;
	BST *temp=new BST(num);
	while(root)
	{
		if(temp->value<root->value)
		{
			num_of_inversions+=root->num_right_subtree+1;
			if(root->Left==NULL)
			{
				root->Left=temp;
				break;
			}
			else
				root=root->Left;
		}
		else
		{
			root->num_right_subtree++;
			if(root->Right==NULL)
			{
				root->Right=temp;
				break;
			}
			else
				root=root->Right;
		}
	}
	return num_of_inversions;
}
void Release_tree(BST *root)
{
	if(root)
	{
		Release_tree(root->Left);
		Release_tree(root->Right);
	}
	delete root;
}
void pre_traversal(BST *root)
{
	if(root)
	{
		pre_traversal(root->Left);
		cout<<root->value<<' ';
		pre_traversal(root->Right);
	}
}
int main()
{
	int n;
	int *tt;
	int i;
	int N_inversions;
	while(cin>>n && n>0)
	{
		N_inversions=0;
		tt=new int[n];
		cin>>tt[0];
		BST *root=new BST(tt[0]);
		for(i=1;i<n;i++)
		{
			cin>>tt[i];
			N_inversions+=Build_tree(root,tt[i]);
		}
		pre_traversal(root);
		cout<<endl;
		cout<<"The number of inversions is :"<<N_inversions<<endl;
		Release_tree(root);
		delete []tt;
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章