Sunday, August 18, 2013

build binary tree


/* From Cracking the Coding Interview 4-3 */
/* Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height. */


node * buildtree(int * n, int a, int b){
    if (b < a) {
        return nullptr;
    }
    int mid = (a + b) / 2;
    node * head = new node(n[mid]);
    head->left = buildtree(n, a, mid - 1);
    head->right = buildtree(n, mid + 1, b);

    return head;
}

void cleantree(node * n){
    if (n->left != nullptr)
        cleantree(n->left);
    if (n->right != nullptr)
        cleantree(n->right);
    delete n;

}

No comments:

Post a Comment