Untitled

mail@pastecode.io avatarunknown
plain_text
24 days ago
2.0 kB
0
Indexable
Never
#include <iostream>
using namespace std;

class Node {
private:
public:
	Node* lchild, * rchild;
	int data;
	int height;
	Node() {
		data = height = 0;
		lchild = rchild = 0;
	}
};

class AVL {
private:
	int getHeight(Node* n) {
		int rHeight, lHeight;
		rHeight = (n && n->rchild) ? n->rchild->height : 0;
		lHeight = (n && n->lchild) ? n->lchild->height : 0;
		return (rHeight > lHeight) ? rHeight + 1 : lHeight + 1;
	}

	int balanceFactor(Node* p) {
		int rHeight, lHeight;
		rHeight = (p && p->rchild) ? p->rchild->height : 0;
		lHeight = (p && p->lchild) ? p->lchild->height : 0;
		return lHeight - rHeight;
	}

	Node* llRotation(Node* p) {
		Node* pl = p->lchild;
		Node* plr = pl->rchild;

		pl->rchild = p;
		p->lchild = plr;

		p->height = getHeight(p);
		pl->height = getHeight(pl);

		if (root == p)
			root = pl;
		return pl;
	}

	Node* lrRotation(Node* p) {

		return p;
	}

	Node* rrRotaion(Node* p) {

		return p;
	}

	Node* rlRotation(Node* p) {

		return p;
	}

	Node* insertHelper(Node* p, int key) {
		Node* t = nullptr;
		if (p == nullptr) {
			t = new Node();
			t->data = key;
			t->height = 1;
			return t;
		}
		if (key < p->data) {
			p->lchild = insertHelper(p->lchild, key);
		}
		else if (key > p->data) {
			p->rchild = insertHelper(p->rchild, key);
		}
		
		p->height = getHeight(p);

		if (balanceFactor(p) == 2 && balanceFactor(p->lchild) == 1)
			return llRotation(p);
		else if (balanceFactor(p) == 2 && balanceFactor(p->lchild) == -1)
			return lrRotation(p);
		else if (balanceFactor(p) == -2 && balanceFactor(p->rchild) == -1)
			return rrRotaion(p);
		else if (balanceFactor(p) == -2 && balanceFactor(p->rchild) == 1)
			return rlRotation(p);

		return p;
	}
public:
	Node* root = 0;

	void insert(int key) {
		root = insertHelper(root, key);
	}
};

AVL tree;

int main()
{
	tree.insert(10);
	tree.insert(5);
	cout << tree.root->data << endl;
	tree.insert(2);

	
	return 0;
}