二叉樹--構造体

3311 ワード

二叉樹--構造体

//========================================//
//    :                    //
//Written By HEWEI                        //
//2011 05 30                              //
//========================================//
#include<iostream>
using namespace std;

#define  MAX 20
//             
struct tree
{
	int left;
	int Data;
	int right;
};

//        
//typedef tree treenode;
//treenode b_tree[MAX];
tree b_tree[MAX];
//    
int nodelist[MAX];

//--------------------------------------//
//---------     -------------------//
//--------------------------------------//
void Create_Tree(int nIndex)
{
	int i;
	int level;  //     
	int Position;//   -1,   1

	b_tree[1].Data = nodelist[0];
	for(i = 1; i< nIndex; i++)
	{
		// i   , nodelist[i]         ,          ,            left or right
		b_tree[i +1].Data = nodelist[i];
		level = 1;
		Position = 0;

		while(Position == 0)
		{
			//nodelist[i]       
			if(nodelist[i] >= b_tree[level].Data)  //  
			{
				//        
				if(b_tree[level].right != -1)  //    
				    level = 2*level +1;
				else 
					Position = 1;
			}
			else  //  
			{
				//        
				if(b_tree[level].left != -1) //    
				    level = 2* level;
				else
					Position = -1;
			}
		}

		if(Position == -1) //  
			b_tree[level].left = i;
		else
			b_tree[level].right = i;
	}
}

//---------------------------------------//
//-------------      --------------//
//---------------------------------------//
void Store_Data(int nIndex)
{
	int temp;
	int i;

	for(i=0; i <nIndex;i++)
	{
		cout << "Please Input the Data => ";
		cin >> temp;
		nodelist[i] = temp;
	}
}
int main(void)
{

	int capacity ; //         
	//   struct 0  
	for(int i = 0; i < MAX; i++)  
	{  
		b_tree[i].left = -1;
		b_tree[i].Data = 0;
		b_tree[i].right = -1;
	}  

	//         
	cout <<"Please Input the capacity : ";  
	cin >> capacity;  
	cout << endl;  
	Store_Data(capacity);  
	//       
	Create_Tree(capacity);  

	//             
	cout <<"Output the content Data of NodeList : " << endl; 
	for(int i= 0; i <capacity; i++)
	{
		cout << nodelist[i] << " ";
	}
	cout << endl;  
	cout <<"Output the content Data of b_tree : " << endl;  
	cout <<"==============================
"; for(int i = 1; i<= MAX; i++) { cout << (i-1) << ": [" << b_tree[i].left<<"]"; cout <<" [" << b_tree[i].Data <<"]"; cout << " [" << b_tree[i].right <<"]"; cout << endl; } return 0; }