Hi, I am trying to balance an AVL tree with 10 nodes. When I run the code in Xcode, it works fine and passes all three tests, but I am getting a timeout error when I try and submit this project. There is an AVLTree class with helper functions in use as well. I am truly lost.
//AVLTree.h
#include <iostream>
class AVLTree {
public:
int data;
uint32_t height;
AVLTree* parent;
AVLTree* left;
AVLTree* right;
//base functions defined for you
AVLTree(int data, AVLTree* parent=nullptr, AVLTree* left=nullptr, AVLTree* right=nullptr);
bool isLeaf();
uint32_t getHeight();
//*******************
//functions you need to define
//insert a node and rebalance tree to maintain AVL balanced tree
//return new root of tree
AVLTree* insert(int data);
//computes a node's balance factor by subtracting the right subtree height from the left subtree height.
int getBalance();
//checks for imbalance and rebalances if neccessary
//return new root of tree
AVLTree* rebalance();
//implement a right rotate
//return new root of tree
AVLTree* rotateRight();
//implement a left rotate
//return new root of tree
AVLTree* rotateLeft();
//Do not edit these three functions
bool isBalanced();
uint32_t countNodes();
void updateHeight();
};
//AVLTree.cpp
#include "AVLTree.h"
#include <iostream>
using namespace std;
//************** already implemented helper functions
AVLTree::AVLTree(int t_data, AVLTree* t_parent, AVLTree* t_left, AVLTree* t_right) {
data = t_data;
height = 0;
parent = t_parent;
left = t_left;
right = t_right;
}
int AVLTree::getBalance() {
int i = (left == nullptr ? 0 : left->height) - (right == nullptr ? 0 : right->height);
int j = abs(i);
return j;
}
AVLTree* AVLTree::rotateRight() {
AVLTree* u = left;
left = u->right;
u->right = this;
return u;
}
AVLTree* AVLTree::rotateLeft() {
AVLTree* u = right;
right = u->left;
u->left = this;
return u;
}
AVLTree* AVLTree::rebalance() {
if (isLeaf()) {
return this;
}
if (left != nullptr) {
left = left -> rebalance();
}
if (right != nullptr) {
right = right -> rebalance();
}
int isBal = isBalanced();
if (!isBal) {
// Rebalance this (me)
if ((left == nullptr ? 0 : left -> getHeight()) < (right == nullptr ? 0 : right -> getHeight())) {
if (right -> left != nullptr) {
right = right -> rotateRight();
AVLTree *t = rotateLeft();
AVLTree* AVLTree::insert(int new_data) {
AVLTree *root = this;
if (new_data < data) {
if (this -> left != nullptr)
{
left = left -> insert(new_data);
}
else {
this -> left = new AVLTree(new_data, this);
}
}
else if (new_data > data) {
if (this -> right != nullptr)
{
right = right -> insert(new_data);
}
else {
this -> right = new AVLTree(new_data, this);
}
}
// always return the root!
root -> updateHeight();