要创建一个高度最小的二叉查找树,就必须让左右子树的节点数量越接近越好。要让数组的中间的值成为根节点。数组左边的一半成为左子树,右边一半成为右子树。
struct Node
{
int value;
Node *left;
Node *right;
};
void createTree(int a[], int begin, int end, Node* &root, Node *parent, bool leftChild)
{
if (begin > end)
{
return;
}
int mid = begin + (end-begin)/2;
Node *p = new Node();
p->value = a[mid];
if (root == NULL)
{
root = p;
}
else
{
if (leftChild)
{
parent->left = p;
}
else
{
parent->right = p;
}
}
if (begin > mid-1)
{
p->left = NULL;
}
else
{
createTree(a, begin, mid-1, root, p, true);
}
if (mid+1 > end)
{
p->right = NULL;
}
else
{
createTree(a, mid+1, end, root, p, false);
}
}