Ejemplo n.º 1
0
/*
bool insertAVL(int, int)
Adds a node to a tree in an attempt to create an AVL tree.
Rotations are implemented, but apparently, incorrectly.
Runtime: theta(n^3)
*/
bool AVLTree::insertAVL(int key, int value) {
	//inc tree size by 1 if going to return true, else don't increment it
	Node* newNode = new Node(key, value, NULL, NULL);
	int arbitrary = 0;
	if (!find(key, arbitrary)) {
		if (root == NULL) {
			size++;
			root = newNode;
			extra.push_back(*root);
			return true;
		}
		else {
			insertHelperAVL(root, key, value);

			//Check if off balance
			if (recursiveGetHeight(newNode->lc) - recursiveGetHeight(newNode->rc) >= 2) {
				//If offbalance, rotate as needed
				if (key <= root->lc->key) {
					SLR(newNode);
				}
				else {
					DLR(newNode);
				}
			}

			//Check if off balance
			if (recursiveGetHeight(newNode->lc) - recursiveGetHeight(newNode->rc) <= -2) {
				//If offbalance, rotate as needed
				if (key >= root->rc->key) {
					SRR(newNode);
				}
				else {
					DRR(newNode);
				}
			}
			size++;
			extra.push_back(*newNode);
			return true;
		}
	}
	//Failed to add the node
	return false;
};
Ejemplo n.º 2
0
nodet* insert( nodet *p,int value)
{
    int balance;
    if (p==NULL)
        return createNode(value);
        if (p->data>value)
        p->left=insert(p->left,value);
    else
        p->right=insert(p->right,value);
            p->height=max(height(p->left),height(p->right))+1;
            balance=balaced(p);
                    if (balance>1 && p->left->data>value)
                        return SRR(p);
                    if (balance<-1 && p->right->data<value)
                        return SRL(p);
                    if (balance>1 && p->left->data<value)
                        return DRR(p);
                    if (balance<-1 && p->right->data>value)
                        return DRL(p);
            else
            return p;
}