preview

Explanation Of A Computer System

Satisfactory Essays

#include
#include //in this version, you only need left //and right rotation, not 4 cases
#include
#include using namespace std;

struct Node
{
int data; struct Node* left; struct Node* right; int height;
};

//a function to calculate height of the tree int height(struct Node* root)
{
if(root == NULL) { return 0; //if there is no node, return 0 } return root->height; //else, repeat the function
}
//a helper function to create a new node faster
Node* newNode(int data)
{
Node* node = new Node(); node->data = data; node->left = NULL; node->right = NULL; node->height = 1; // new node is added at leaf return (node); //return the pointer to the newly created node
}
//rotations
Node* rightRotate(Node* input)
{
Node* x …show more content…

If this node is unbalanced, there are 4 cases //Left Left case //notice balance will change depends on how you //calculate your balance factor if(balance > 1 && data < node->left->data) { return rightRotate(node); }

//Right Right case if(balance < -1 && data > node->right->data) { return leftRotate(node); }

//Left Right case if(balance > 1 && data > node->left->data) { node->left = leftRotate(node->left); return rightRotate(node); }

//Right Left case if(balance < -1 && data < node->right->data) { //swapping using rightRotate, since it is a pointer node->right = rightRotate(node->right); return leftRotate(node); }

//return the (unchanged) node pointer return node; }

Node* FindMinNode(Node* root) //find the minimum value node in the tree
{
Node* current = root; //keep traversing to the leftest leaf since it WILL be in the left while(current->left != NULL) { current = current->left; } return current;
}

//recursion are like moving from stations to
//stations
Node* deleteNode(Node* root, int data)
{
//1. Perform standard BST delete if(root == NULL) { return root; } //if the key to be deleted is smaller than //root's key, then go left, recursively if( data < root->data) { root->left = deleteNode(root->left, data); }

//if the key to be deleted is bigger than //root's key, then go right, recursively else if(data > root->data) { root->right =

Get Access