如果要按索引顺序插入整数,则需要将索引转换为从根到应插入位置的路径,
0 -> ""
1 -> "L"
2 -> "R"
3 -> "LL"
4 -> "LR"
5 -> "RL"
...
然后从根节点找到插入的地方。将索引转换为路径很容易,一旦你知道它就跟随路径,但在我看来,更容易的是以不同的顺序插入整数,递归地首先填充左子树,然后是右子树。
// get us a new pointer to a properly NULL-initialised tree
tree *newEmptyTree(void) {
tree *new = malloc(sizeof *new);
if (!new) {
fputs(stderr, "Allocation of tree* failed.");
exit(EXIT_FAILURE);
}
new->data = NULL;
new->l = NULL;
new->r = NULL;
return new;
}
// make a heap from part of an array
tree *heap_from_array(int arr[], int index, int elements) {
// when we're past the end of the array, there's nothing to do anymore
if (index >= elements) return NULL;
// Otherwise, get us a new tree
tree *this = newEmptyTree();
// store current element
this->data = arr[index];
// fill left subtree
this->l = heap_from_array(arr, 2*index + 1, elements);
// fill right
this-> r = heap_from_array(arr, 2*index + 2, elements);
// done, return the thing
return this;
}
并将其用于
void insert1( tree * root,int arr[],int n) {
// check whether root is not NULL
if (!root) {
fputs(stderr, "Got a NULL root, can't insert.");
exit(1);
}
// now let's hope that root is a valid pointer
// first check whether the array does contain elements
if (n < 0) {
fputs(stderr, "Got no array elements, can't insert.");
exit(EXIT_FAILURE);
}
// okiedokie, get going
root->data = arr[0];
root->l = heap_from_array(arr, 1, n);
root->r = heap_from_array(arr, 2, n);
// done :D
}