Skip to main content

AVL tree and other homeworks


AVL Tree:

#include<stdio.h>
#include<stdlib.h>

// An AVL tree node
struct Node
{
    int key;
    struct Node *left;
    struct Node *right;
    int height;
};
int max(int a, int b);

// A utility function to get the height of the tree
int height(struct Node *N)
{
    if (N == NULL)
        return 0;
    return N->height;
}

// A utility function to get maximum of two integers
int max(int a, int b)
{
    return (a > b)? a : b;
}

/* Helper function that allocates a new node with the given key and
    NULL left and right pointers. */
struct Node* newNode(int key)
{
    struct Node* node = (struct Node*)
                        malloc(sizeof(struct Node));
    node->key   = key;
    node->left   = NULL;
    node->right  = NULL;
    node->height = 1;  // new node is initially added at leaf
    return(node);
}

// A utility function to right rotate subtree rooted with y
// See the diagram given above.
struct Node *rightRotate(struct Node *y)
{
    struct Node *x = y->left;
    struct Node *T2 = x->right;

    // Perform rotation
    x->right = y;
    y->left = T2;

    // Update heights
    y->height = max(height(y->left), height(y->right))+1;
    x->height = max(height(x->left), height(x->right))+1;

    // Return new root
    return x;
}

// A utility function to left rotate subtree rooted with x
// See the diagram given above.
struct Node *leftRotate(struct Node *x)
{
    struct Node *y = x->right;
    struct Node *T2 = y->left;

    // Perform rotation
    y->left = x;
    x->right = T2;

    //  Update heights
    x->height = max(height(x->left), height(x->right))+1;
    y->height = max(height(y->left), height(y->right))+1;

    // Return new root
    return y;
}

// Get Balance factor of node N
int getBalance(struct Node *N)
{
    if (N == NULL)
        return 0;
    return height(N->left) - height(N->right);
}

// Recursive function to insert a key in the subtree rooted
// with node and returns the new root of the subtree.
struct Node* insert(struct Node* node, int key)
{
    /* 1.  Perform the normal BST insertion */
    if (node == NULL)
        return(newNode(key));

    if (key < node->key)
        node->left  = insert(node->left, key);
    else if (key > node->key)
        node->right = insert(node->right, key);
    else // Equal keys are not allowed in BST
        return node;

    /* 2. Update height of this ancestor node */
    node->height = 1 + max(height(node->left),
                           height(node->right));

    /* 3. Get the balance factor of this ancestor
          node to check whether this node became
          unbalanced */
    int balance = getBalance(node);

    // If this node becomes unbalanced, then
    // there are 4 cases

    // Left Left Case
    if (balance > 1 && key < node->left->key)
        return rightRotate(node);

    // Right Right Case
    if (balance < -1 && key > node->right->key)
        return leftRotate(node);

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

    // Right Left Case
    if (balance < -1 && key < node->right->key)
    {
        node->right = rightRotate(node->right);
        return leftRotate(node);
    }

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

// A utility function to print preorder traversal
// of the tree.
// The function also prints height of every node
void preOrder(struct Node *root)
{
    if(root != NULL)
    {
        printf("%d ", root->key);
        preOrder(root->left);
        preOrder(root->right);
    }
}

/* Driver program to test above function*/
int main()
{
  struct Node *root = NULL;

  /* Constructing tree given in the above figure */
  root = insert(root, 10);
  root = insert(root, 20);
  root = insert(root, 30);
  root = insert(root, 40);
  root = insert(root, 50);
  root = insert(root, 25);

  preOrder(root);

  return 0;
}


Success #stdin #stdout 0s 9424KB

 stdin


Standard input is empty


 stdout

30 20 10 25 40 50 

Splay tree:

#include<stdio.h> 
#include<stdlib.h> 
  
// An AVL tree node 
struct node 
{ 
    int key; 
    struct node *left, *right; 
}; 
struct node* newNode(int key) 
{ 
    struct node* node = (struct node*)malloc(sizeof(struct node)); 
    node->key   = key; 
    node->left  = node->right  = NULL; 
    return (node); 
} 
  
struct node *rightRotate(struct node *x) 
{ 
    struct node *y = x->left; 
    x->left = y->right; 
    y->right = x; 
    return y; 
} 
  
struct node *leftRotate(struct node *x) 
{ 
    struct node *y = x->right; 
    x->right = y->left; 
    y->left = x; 
    return y; 
} 
  
// This function brings the key at root if key is present in tree. 
// If key is not present, then it brings the last accessed item at 
// root.  This function modifies the tree and returns the new root 
struct node *splay(struct node *root, int key) 
{ 
    // Base cases: root is NULL or key is present at root 
    if (root == NULL || root->key == key) 
        return root; 
  
    // Key lies in left subtree 
    if (root->key > key) 
    { 
        // Key is not in tree, we are done 
        if (root->left == NULL) return root; 
  
        // Zig-Zig (Left Left) 
        if (root->left->key > key) 
        { 
            // First recursively bring the key as root of left-left 
            root->left->left = splay(root->left->left, key); 
  
            // Do first rotation for root, second rotation is done after else 
            root = rightRotate(root); 
        } 
        else if (root->left->key < key) // Zig-Zag (Left Right) 
        { 
            // First recursively bring the key as root of left-right 
            root->left->right = splay(root->left->right, key); 
  
            // Do first rotation for root->left 
            if (root->left->right != NULL) 
                root->left = leftRotate(root->left); 
        } 
  
        // Do second rotation for root 
        return (root->left == NULL)? root: rightRotate(root); 
    } 
    else // Key lies in right subtree 
    { 
        // Key is not in tree, we are done 
        if (root->right == NULL) return root; 
  
        // Zag-Zig (Right Left) 
        if (root->right->key > key) 
        { 
            // Bring the key as root of right-left 
            root->right->left = splay(root->right->left, key); 
  
            // Do first rotation for root->right 
            if (root->right->left != NULL) 
                root->right = rightRotate(root->right); 
        } 
        else if (root->right->key < key)// Zag-Zag (Right Right) 
        { 
            // Bring the key as root of right-right and do first rotation 
            root->right->right = splay(root->right->right, key); 
            root = leftRotate(root); 
        } 
  
        // Do second rotation for root 
        return (root->right == NULL)? root: leftRotate(root); 
    } 
} 
  
// The search function for Splay tree.  Note that this function 
// returns the new root of Splay Tree.  If key is present in tree 
// then, it is moved to root. 
struct node *search(struct node *root, int key) 
{ 
    return splay(root, key); 
} 
  
// A utility function to print preorder traversal of the tree. 
// The function also prints height of every node 
void preOrder(struct node *root) 
{ 
    if (root != NULL) 
    { 
        printf("%d ", root->key); 
        preOrder(root->left); 
        preOrder(root->right); 
    } 
} 
  
/* Driver program to test above function*/
int main() 
{ 
    struct node *root = newNode(100); 
    root->left = newNode(50); 
    root->right = newNode(200); 
    root->left->left = newNode(40); 
    root->left->left->left = newNode(30); 
    root->left->left->left->left = newNode(20); 
  
    root = search(root, 20); 
    printf("Preorder traversal of the modified Splay tree is \n"); 
    preOrder(root); 
    return 0; 
} 
Success #stdin #stdout 0s 9424KB
Preorder traversal of the modified Splay tree is 
20 50 30 40 100 200 

Queue using two stacks:

#include <stdio.h> #include <stdlib.h> typedef struct sNode { int data; struct sNode* next; }stack; void push(stack** top_ref, int new_data); int pop(stack** top_ref); /* structure of queue having two stacks */ struct queue { stack* stack1; stack* stack2; }; void enQueue(struct queue* q, int x) { push(&q->stack1, x); //& refers to the value in the address } int deQueue(struct queue* q) { int x; /* If both stacks are empty then error */ if (q->stack1 == NULL && q->stack2 == NULL) { printf("Q is empty"); getchar(); exit(0); } /* Move elements from stack1 to stack 2 only if stack2 is empty */ if (q->stack2 == NULL) { while (q->stack1 != NULL) { x = pop(&q->stack1); push(&q->stack2, x); } } x = pop(&q->stack2); return x; } /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data) { /* allocate node */ struct sNode* new_node = (struct sNode*)malloc(sizeof(struct sNode)); if (new_node == NULL) { printf("Stack overflow \n"); getchar(); exit(0); } /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*top_ref); /* move the head to point to the new node */ (*top_ref) = new_node; } /* Function to pop an item from stack*/ int pop(struct sNode** top_ref) { int res; struct sNode* top; /*If stack is empty then error */ if (*top_ref == NULL) { printf("Stack underflow \n"); getchar(); exit(0); } else { top = *top_ref; res = top->data; *top_ref = top->next; free(top); return res; } } /* Driver program*/ int main() { struct queue* q = (struct queue*)malloc(sizeof(struct queue)); q->stack1 = NULL; q->stack2 = NULL; enQueue(q, 1); enQueue(q, 2); enQueue(q, 3); printf("%d ", deQueue(q)); printf("%d ", deQueue(q)); printf("%d ", deQueue(q)); return 0; }

 stdout

1 2 3 
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. struct node
  4. {
  5. int key;
  6. struct node *left, *right;
  7. };
  8. // A utility function to create a new BST node
  9. struct node *newNode(int item)
  10. {
  11. struct node *temp = (struct node *)malloc(sizeof(struct node));
  12. temp->key = item;
  13. temp->left = temp->right = NULL;
  14. return temp;
  15. }
  16. // A utility function to do inorder traversal of BST
  17. void inorder(struct node *root)
  18. {
  19. if (root != NULL)
  20. {
  21. inorder(root->left);
  22. printf("%d ", root->key);
  23. inorder(root->right);
  24. }
  25. }
  26. /* A utility function to insert a new node with given key in BST */
  27. struct node* insert(struct node* node, int key)
  28. {
  29. /* If the tree is empty, return a new node */
  30. if (node == NULL) return newNode(key);
  31. /* Otherwise, recur down the tree */
  32. if (key < node->key)
  33. node->left = insert(node->left, key);
  34. else
  35. node->right = insert(node->right, key);
  36. /* return the (unchanged) node pointer */
  37. return node;
  38. }
  39. struct node * minValueNode(struct node* node)
  40. {
  41. struct node* current = node;
  42. /* loop down to find the leftmost leaf */
  43. while (current->left != NULL)
  44. current = current->left;
  45. return current;
  46. }
  47. struct node* deleteNode(struct node* root, int key)
  48. {
  49. // base case
  50. if (root == NULL) return root;
  51. // If the key to be deleted is smaller than the root's key,
  52. // then it lies in left subtree
  53. if (key < root->key)
  54. root->left = deleteNode(root->left, key);
  55. // If the key to be deleted is greater than the root's key,
  56. // then it lies in right subtree
  57. else if (key > root->key)
  58. root->right = deleteNode(root->right, key);
  59. // if key is same as root's key, then This is the node
  60. // to be deleted
  61. else
  62. {
  63. // node with only one child or no child
  64. if (root->left == NULL)
  65. {
  66. struct node *temp = root->right;
  67. free(root);
  68. return temp;
  69. }
  70. else if (root->right == NULL)
  71. {
  72. struct node *temp = root->left;
  73. free(root);
  74. return temp;
  75. }
  76. // node with two children: Get the inorder successor (smallest
  77. // in the right subtree)
  78. struct node* temp = minValueNode(root->right);
  79. // Copy the inorder successor's content to this node
  80. root->key = temp->key;
  81. // Delete the inorder successor
  82. root->right = deleteNode(root->right, temp->key);
  83. }
  84. return root;
  85. }
  86. // Driver Program to test above functions
  87. int main()
  88. {
  89. struct node *root = NULL;
  90. root = insert(root, 50);
  91. root = insert(root, 30);
  92. root = insert(root, 20);
  93. root = insert(root, 40);
  94. root = insert(root, 70);
  95. root = insert(root, 60);
  96. root = insert(root, 80);
  97. printf("Inorder traversal of the given tree \n");
  98. inorder(root);
  99. printf("\nDelete 20\n");
  100. root = deleteNode(root, 20);
  101. printf("Inorder traversal of the modified tree \n");
  102. inorder(root);
  103. printf("\nDelete 30\n");
  104. root = deleteNode(root, 30);
  105. printf("Inorder traversal of the modified tree \n");
  106. inorder(root);
  107. printf("\nDelete 50\n");
  108. root = deleteNode(root, 50);
  109. printf("Inorder traversal of the modified tree \n");
  110. inorder(root);
  111. return 0;
  112. }
Success #stdin #stdout 0s 9424KB
 stdin
Standard input is empty
 stdout
Inorder traversal of the given tree 
20 30 40 50 60 70 80 
Delete 20
Inorder traversal of the modified tree 
30 40 50 60 70 80 
Delete 30
Inorder traversal of the modified tree 
40 50 60 70 80 
Delete 50
Inorder traversal of the modified tree 
40 60 70 80 

These codes are not written by the site owner. To complete the data structure portion, these are mentioned here. Feel free to contact for any details regarding this.


Comments

Popular posts from this blog

Mastering SQL for Data Science: Top SQL Interview Questions by Experience Level

Introduction: SQL (Structured Query Language) is a cornerstone of data manipulation and querying in data science. SQL technical rounds are designed to assess a candidate’s ability to work with databases, retrieve, and manipulate data efficiently. This guide provides a comprehensive list of SQL interview questions segmented by experience level—beginner, intermediate, and experienced. For each level, you'll find key questions designed to evaluate the candidate’s proficiency in SQL and their ability to solve data-related problems. The difficulty increases as the experience level rises, and the final section will guide you on how to prepare effectively for these rounds. Beginner (0-2 Years of Experience) At this stage, candidates are expected to know the basics of SQL, common commands, and elementary data manipulation. What is SQL? Explain its importance in data science. Hint: Think about querying, relational databases, and data manipulation. What is the difference between WHERE

What is Bort?

 Introduction: Bort, is the new and more optimized version of BERT; which came out this october from amazon science. I came to know about it today while parsing amazon science's news on facebook about bort. So Bort is the newest addition to the long list of great LM models with extra-ordinary achievements.  Why is Bort important? Bort, is a model of 5.5% effective and 16% total size of the original BERT model; and is 20x faster than BERT, while being able to surpass the BERT model in 20 out of 23 tasks; to quote the abstract of the paper,  ' it obtains performance improvements of between 0 . 3% and 31%, absolute, with respect to BERT-large, on multiple public natural language understanding (NLU) benchmarks. ' So what made this achievement possible? The main idea behind creation of Bort is to go beyond the shallow depth of weight pruning, connection deletion or merely factoring the NN into different matrix factorizations and thus distilling it. While methods like knowle

Spacy errors and their solutions

 Introduction: There are a bunch of errors in spacy, which never makes sense until you get to the depth of it. In this post, we will analyze the attribute error E046 and why it occurs. (1) AttributeError: [E046] Can't retrieve unregistered extension attribute 'tag_name'. Did you forget to call the set_extension method? Let's first understand what the error means on superficial level. There is a tag_name extension in your code. i.e. from a doc object, probably you are calling doc._.tag_name. But spacy suggests to you that probably you forgot to call the set_extension method. So what to do from here? The problem in hand is that your extension is not created where it should have been created. Now in general this means that your pipeline is incorrect at some level.  So how should you solve it? Look into the pipeline of your spacy language object. Chances are that the pipeline component which creates the extension is not included in the pipeline. To check the pipe eleme