2.输入:一个有序数组和数组大小
输出:一个有序二叉树(二叉查找树又叫二叉排序树)它只是说是有序二叉树没有说是平衡的,当且当做是平衡的吧!
#include <iostream>
using namespace std;
struct BTreeNode{
int val;
struct BTreeNode *left;
struct BTreeNode *right;
};
void Convert(int array[],int arraysize,struct BTreeNode **root)
{
if(arraysize==0)
return;
if(arraysize==1)
{
*root=(struct BTreeNode*)malloc(sizeof(struct BTreeNode));
(*root)->val=array[0];
cout<<(*root)->val<<endl;
(*root)->left=NULL;
(*root)->right=NULL;
return;
}
int mid=arraysize/2;
*root=(struct BTreeNode*)malloc(sizeof(struct BTreeNode));
(*root)->val=array[mid];
cout<<(*root)->val<<endl;
Convert(array,mid,&(*root)->left);
Convert(array+mid+1,arraysize-mid-1,&(*root)->right);
}
void printTree(struct BTreeNode *root)
{
if(root!=NULL)
{
printTree(root->left);
cout<<root->val;
printTree(root->right);
}
}
int main()
{
int array[]={1,2,3,4,5,6,7};
struct BTreeNode *root;
Convert(array,7,&root);
printTree(root);
cout<<endl;
return 0;
}
输出结果为:
4
2
1
3
6
5
7
1234567
平衡二叉查找树:
4
2 6
1 3 5 7