C++实现二叉树

#include <iostream>
using namespace std ;
class Tree
{
    public :
        int number ;
        class Tree *left ;
        class Tree *right ;
        void insert_tree(class Tree **header , int number) ;
        void print_tree(class Tree *header , int lever) ;
        void front(class Tree *header) ;
        void middle(class Tree *header) ;
        void back(class Tree *header) ;
};

int main()
{
    Tree tree ;
    Tree *header = NULL ;
    int i ;
    int buffer[10] ;
    for(i = 0 ; i < 10 ; i++)
    {
        buffer[i] = rand()%100 ;
    }
     for(i = 0 ; i < 10 ; i++)
    {
        tree.insert_tree(&header , buffer[i]) ;
    }
    tree.print_tree(header,0);
    cout << endl<< "前序遍历: " <<endl ;
    tree.front(header) ;
    cout << endl << "中序遍历: "<< endl ;
    tree.middle(header) ;
    cout << endl << "后序遍历: " << endl ;
    tree.back(header);
    getchar();
}

void Tree::insert_tree(class Tree **header , int number)
{
    Tree *New = NULL ;
    New = new Tree[10] ;
    if(NULL == New)
	   return ;
	New->number = number ;
    New->left = NULL ;
    New->right = NULL ;
	Tree **link = header ;
	Tree *cur ;
	while(cur = *link)
	{
		if(New->number < cur->number)
			link = &(cur->left) ;
		else
			link = &(cur->right) ;
	}
	*link = New ;
}
void Tree::print_tree(Tree *header , int lever)
{
    if(header == NULL)
		return ; 

	print_tree(header->right , lever+1);
	int i ;
	for(i = 0 ; i < lever ; i++)
		cout<<'\t';
	cout << header->number << endl;
	print_tree(header->left , lever+1);
}

void Tree::front(class Tree *header)
{
    if(header == NULL)
		return ;
	cout <<' '<<header->number ;
	front(header->left);
	front(header->right);
}

void Tree::middle(class Tree *header)
{
    if(header == NULL)
		return ;
	middle(header->left);
    cout<<' '<< header->number ;
	middle(header->right);
}

void Tree::back(class Tree *header)
{
    if(header == NULL)
		return ;
	back(header->left);
	back(header->right);
	cout <<' '<<header->number ;
}
上一篇:浅谈JavaScript中的defer,async


下一篇:CentOs6.7 python2.6升级到2.7.11