一个有序数组转为二叉排序树

输入:一个有序数组和数组大小

输出:一个有序二叉树(二叉查找树又叫二叉排序树)它只是说是有序二叉树没有说是平衡的,当且当做是平衡的吧!

#ifndef TREE_H
#define TREE_H
#include<cstdio>
#include<iostream>
#include<vector>
using namespace std;
struct Tree
{

	Tree* Lchild;
	Tree* Rchild;
	
	int value; 
};

#endif



#include"Tree.h"
	
Tree *AddNode(vector<int> a,int min,int max)
{
	Tree *root;
	int mid;
	
	if(min>max)return NULL;
	else
	{
		mid=(min+max)/2;
		root=new Tree();
		root->value=a[mid];
		root->Lchild=AddNode(a,min,mid-1);
		root->Rchild =AddNode(a,mid+1,max);
		return root;
	}
}

void printfTree(Tree *node)
{
	if(node!=NULL)
	{
		cout<<node->value<<endl;
		cout<<"-lchild "<<endl;
		printfTree(node->Lchild);
		cout<<"-rchild "<<endl;
		printfTree(node->Rchild);
	}
}

int main()
{
	vector<int >a;
	Tree *root;
	int n;
	int element;
	cout<<":";
	cin>>n;
	for(int i=0;i<n;i++)
	{
		cin>>element;
		a.push_back(element);
	}

	root=AddNode(a,0,n-1);
	printfTree(root);
	cin>>n;
}

 

posted @ 2013-03-06 17:03  宁静致远--Ada  阅读(426)  评论(0编辑  收藏  举报