简体   繁体   中英

function to rebalance binary search tree

I am working on implementing a binary search tree. One of the functions required to complete the implementation is a rebalance function.

According to the specifications the function works in the following way:

The rebalance() method should create a balanced tree and thereby reduce skewness to zero. A balanced tree is one in which the size of the left and right subtrees differ by no more than 1, throughout the tree (ie, every subtree is also balanced).

To balance the tree, the rebalance() method should repeatedly move the root value to the smaller subtree, and move the min/max value from the larger subtree to the root, until the tree is balanced. It should then recursively balance both subtrees.

So far I have the following code:

    struct treeNode {
    Type value;
    int count;
    treeNode* left;
    treeNode* right;
    };
    treeNode* root;

template <class Type>
void bstree<Type>::rebalance(treeNode* sroot){

    if (root == NULL) {
        throw new underflow_error("tree is empty");
    }

    while (skewness(sroot) != 0)
    {
        if (size(sroot->left) < size(sroot->right))
        {
            sroot->left.insert(sroot->value);
            sroot->left.insert(max(sroot->right));
            sroot->left.insert(min(sroot->right));

        }
        else
        {
            sroot->right.insert(sroot->value);
            sroot->left.insert(max(sroot->left));
            sroot->left.insert(min(sroot->left));
        }
    }

    rebalance(sroot->left);
    rebalance(sroot->right);
}

I can't tell if I have followed the specifications correctly or not. Can I get some insight or pointers as where I may have done things wrong?

You have not followed the specifications correctly. For one thing, your rebalance operation increases the size of the tree. For another, the result is not always a binary search tree.

You must understand how these trees work before you attempt to implement them. There is just no way around that. I advise you to study your text (or wikipedia ) and try constructing and balancing some trees with pencil and paper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM