Question

Write a C function for each of the following, must be between 10 - 20 lines,...

Write a C function for each of the following, must be between 10 - 20 lines, include all assertions:

Binary Search Tree Insert

Binary Search Tree Remove

Binary Search Tree Traversal (Iterative version with a given stack)

Binary Heap Insert

Binary Heap Remove

0 0
Add a comment Improve this question Transcribed image text
Answer #1

1) INSERT

/* A utility function to insert a new node with given key in BST */

struct node* insert(struct node* node, int key)

{

    /* If the tree is empty, return a new node */

    if (node == NULL) return newNode(key);

  

    /* Otherwise, recur down the tree */

    if (key < node->key)

        node->left = insert(node->left, key);

    else if (key > node->key)

        node->right = insert(node->right, key);   

  

    /* return the (unchanged) node pointer */

    return node;

}

2) REMOVE

/* Given a binary search tree and a key, this function deletes the key

   and returns the new root */

struct node* deleteNode(struct node* root, int key)

{

    // base case

    if (root == NULL) return root;

  

    // If the key to be deleted is smaller than the root's key,

    // then it lies in left subtree

    if (key < root->key)

        root->left = deleteNode(root->left, key);

  

    // If the key to be deleted is greater than the root's key,

    // then it lies in right subtree

    else if (key > root->key)

        root->right = deleteNode(root->right, key);

  

    // if key is same as root's key, then This is the node

    // to be deleted

    else

    {

        // node with only one child or no child

        if (root->left == NULL)

        {

            struct node *temp = root->right;

            free(root);

            return temp;

        }

        else if (root->right == NULL)

        {

            struct node *temp = root->left;

            free(root);

            return temp;

        }

  

        // node with two children: Get the inorder successor (smallest

        // in the right subtree)

        struct node* temp = minValueNode(root->right);

  

        // Copy the inorder successor's content to this node

        root->key = temp->key;

  

        // Delete the inorder successor

        root->right = deleteNode(root->right, temp->key);

    }

    return root;

}

3) ITERATIVE INORDER TRAVERSAL

/* Iterative function for inorder tree traversal */

void inOrder(struct Node *root)

{

  /* set current to root of binary tree */

  struct Node *current = root;

  struct sNode *s = NULL; /* Initialize stack s */

  bool done = 0;

  

  while (!done)

  {

    /* Reach the left most tNode of the current tNode */

    if(current != NULL)

    {

      /* place pointer to a tree node on the stack before traversing

        the node's left subtree */

      push(&s, current);                                               

      current = current->left;  

    }

         

    /* backtrack from the empty subtree and visit the tNode

       at the top of the stack; however, if the stack is empty,

      you are done */

    else                                                              

    {

      if (!isEmpty(s))

      {

        current = pop(&s);

        printf("%d ", current->data);

  

        /* we have visited the node and its left subtree.

          Now, it's right subtree's turn */

        current = current->right;

      }

      else

        done = 1;

    }

  } /* end of while */  

}     

NOTE: As per Chegg policy, I am allowed to answer only 3 questions (including sub-parts) on a single post. Kindly post the remaining questions separately and I will try to answer them. Sorry for the inconvenience caused.

Add a comment
Answer #2

Sure, here are C functions for each of the specified operations. Please note that the provided implementations are basic and may require further refinement depending on the specific requirements of your application.

  1. Binary Search Tree Insert:

cCopy code#include <stdio.h>#include <stdlib.h>#include <assert.h>struct TreeNode {
    int data;    struct TreeNode* left;
    struct TreeNode* right;};struct TreeNode* insert(struct TreeNode* root, int value) {    if (root == NULL) {        struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
        assert(newNode != NULL);
        newNode->data = value;
        newNode->left = NULL;
        newNode->right = NULL;        return newNode;
    }    if (value < root->data) {
        root->left = insert(root->left, value);
    } else if (value > root->data) {
        root->right = insert(root->right, value);
    }    return root;
}
  1. Binary Search Tree Remove:

cCopy codestruct TreeNode* findMin(struct TreeNode* node) {    struct TreeNode* current = node;    while (current->left != NULL) {
        current = current->left;
    }    return current;
}struct TreeNode* removeNode(struct TreeNode* root, int value) {    if (root == NULL) {        return root;
    }    if (value < root->data) {
        root->left = removeNode(root->left, value);
    } else if (value > root->data) {
        root->right = removeNode(root->right, value);
    } else {        if (root->left == NULL) {            struct TreeNode* temp = root->right;            free(root);            return temp;
        } else if (root->right == NULL) {            struct TreeNode* temp = root->left;            free(root);            return temp;
        }        struct TreeNode* temp = findMin(root->right);
        root->data = temp->data;
        root->right = removeNode(root->right, temp->data);
    }    return root;
}
  1. Binary Search Tree Traversal (Iterative version with a given stack):

cCopy code#include <stdio.h>#include <stdlib.h>#include <assert.h>struct TreeNode {
    int data;    struct TreeNode* left;
    struct TreeNode* right;};struct StackNode {
    struct TreeNode* node;
    struct StackNode* next;};struct Stack {
    struct StackNode* top;};struct Stack* createStack() {    struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
    assert(stack != NULL);    stack->top = NULL;    return stack;
}int isEmpty(struct Stack* stack) {    return stack->top == NULL;
}void push(struct Stack* stack, struct TreeNode* node) {    struct StackNode* newNode = (struct StackNode*)malloc(sizeof(struct StackNode));
    assert(newNode != NULL);
    newNode->node = node;
    newNode->next = stack->top;    stack->top = newNode;
}struct TreeNode* pop(struct Stack* stack) {    if (isEmpty(stack)) {        return NULL;
    }    struct StackNode* temp = stack->top;    stack->top = stack->top->next;    struct TreeNode* poppedNode = temp->node;    free(temp);    return poppedNode;
}void inorderTraversal(struct TreeNode* root) {    if (root == NULL) {        return;
    }    struct Stack* stack = createStack();    struct TreeNode* current = root;    while (current != NULL || !isEmpty(stack)) {        while (current != NULL) {
            push(stack, current);
            current = current->left;
        }

        current = pop(stack);        printf("%d ", current->data);

        current = current->right;
    }    free(stack);
}
  1. Binary Heap Insert:

cCopy code#include <stdio.h>#include <stdlib.h>#include <assert.h>struct BinaryHeap {
    int* arr;    int capacity;    int size;
};struct BinaryHeap* createBinaryHeap(int capacity) {    struct BinaryHeap* heap = (struct BinaryHeap*)malloc(sizeof(struct BinaryHeap));
    assert(heap != NULL);
    heap->arr = (int*)malloc(sizeof(int) * capacity);
    assert(heap->arr != NULL);
    heap->capacity = capacity;
    heap->size = 0;    return heap;
}void swap(int* a, int* b) {    int temp = *a;
    *a = *b;
    *b = temp;
}void heapifyUp(struct BinaryHeap* heap, int index) {    while (index > 0 && heap->arr[(index - 1) / 2] > heap->arr[index]) {
        swap(&heap->arr[(index - 1) / 2], &heap->arr[index]);
        index = (index - 1) / 2;
    }
}void insert(struct BinaryHeap* heap, int value) {    if (heap->size == heap->capacity) {        return;
    }

    heap->arr[heap->size] = value;
    heapifyUp(heap, heap->size);
    heap->size++;
}
  1. Binary Heap Remove:

cCopy codevoid heapifyDown(struct BinaryHeap* heap, int index) {    int smallest = index;    int left = 2 * index + 1;    int right = 2 * index + 2;    if (left < heap->size && heap->arr[left] < heap->arr[smallest]) {
        smallest = left;
    }    if (right <


answered by: Mayre Yıldırım
Add a comment
Answer #3

Sure, here are the C functions for each of the specified operations with assertions:

  1. Binary Search Tree Insert:

cCopy code#include <stdio.h>#include <stdlib.h>#include <assert.h>typedef struct TreeNode {
    int data;    struct TreeNode* left;
    struct TreeNode* right;} TreeNode;

TreeNode* createNode(int value) {
    TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode));
    newNode->data = value;
    newNode->left = NULL;
    newNode->right = NULL;    return newNode;
}

TreeNode* insert(TreeNode* root, int value) {    if (root == NULL) {        return createNode(value);
    }    if (value < root->data) {
        root->left = insert(root->left, value);
    } else if (value > root->data) {
        root->right = insert(root->right, value);
    }    return root;
}int main() {
    TreeNode* root = NULL;
    root = insert(root, 50);
    root = insert(root, 30);
    root = insert(root, 70);
    root = insert(root, 20);
    root = insert(root, 40);

    assert(root->data == 50);
    assert(root->left->data == 30);
    assert(root->right->data == 70);
    assert(root->left->left->data == 20);
    assert(root->left->right->data == 40);    printf("Binary Search Tree Insert test passed!\n");    return 0;
}
  1. Binary Search Tree Remove:

cCopy code#include <stdio.h>#include <stdlib.h>#include <assert.h>typedef struct TreeNode {
    int data;    struct TreeNode* left;
    struct TreeNode* right;} TreeNode;

TreeNode* createNode(int value) {
    TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode));
    newNode->data = value;
    newNode->left = NULL;
    newNode->right = NULL;    return newNode;
}

TreeNode* findMin(TreeNode* node) {    while (node->left != NULL) {
        node = node->left;
    }    return node;
}

TreeNode* removeNode(TreeNode* root, int value) {    if (root == NULL) {        return root;
    }    if (value < root->data) {
        root->left = removeNode(root->left, value);
    } else if (value > root->data) {
        root->right = removeNode(root->right, value);
    } else {        if (root->left == NULL) {
            TreeNode* temp = root->right;            free(root);            return temp;
        } else if (root->right == NULL) {
            TreeNode* temp = root->left;            free(root);            return temp;
        }

        TreeNode* temp = findMin(root->right);
        root->data = temp->data;
        root->right = removeNode(root->right, temp->data);
    }    return root;
}int main() {
    TreeNode* root = NULL;
    root = createNode(50);
    root->left = createNode(30);
    root->right = createNode(70);
    root->left->left = createNode(20);
    root->left->right = createNode(40);

    root = removeNode(root, 30);

    assert(root->left->data == 20);
    assert(root->left->right == NULL);    printf("Binary Search Tree Remove test passed!\n");    return 0;
}
  1. Binary Search Tree Traversal (Iterative version with a given stack):

cCopy code#include <stdio.h>#include <stdlib.h>#include <assert.h>typedef struct TreeNode {
    int data;    struct TreeNode* left;
    struct TreeNode* right;} TreeNode;typedef struct StackNode {
    TreeNode* node;    struct StackNode* next;} StackNode;

StackNode* createStackNode(TreeNode* treeNode) {
    StackNode* stackNode = (StackNode*)malloc(sizeof(StackNode));
    stackNode->node = treeNode;
    stackNode->next = NULL;    return stackNode;
}void push(StackNode** top, TreeNode* treeNode) {
    StackNode* stackNode = createStackNode(treeNode);
    stackNode->next = *top;
    *top = stackNode;
}

TreeNode* pop(StackNode** top) {    if (*top == NULL) {        return NULL;
    }
    StackNode* temp = *top;
    *top = (*top)->next;
    TreeNode* treeNode = temp->node;    free(temp);    return treeNode;
}void inorderTraversal(TreeNode* root) {
    StackNode* stack = NULL;
    TreeNode* current = root;    while (current != NULL || stack != NULL) {        while (current != NULL) {
            push(&stack, current);
            current = current->left;
        }

        current = pop(&stack);        printf("%d ", current->data);

        current = current->right;
    }
}int main() {
    TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
    root->data = 50;
    root->left = (TreeNode*)malloc(sizeof(TreeNode));
    root->left->data = 30;
    root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
    root->left->left->data = 20;
    root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
    root->left->right->data = 40;
    root->right = (TreeNode*)malloc(sizeof(TreeNode));
    root->right->data = 70;    printf("Inorder Traversal: ");
    inorderTraversal(root);    printf("\n");

    assert(root->data == 50);
    assert(root->left->data == 30);
    assert(root->left->left->data == 20);
    assert(root->left->right->data == 40);
    assert(root->right->data == 70);    printf("Binary Search Tree Traversal test passed!\n");    return 0;
}
  1. Binary Heap Insert:

c

#include <stdio.h>#include <stdlib.h>#include <assert.h>typedef struct BinaryHeap {    int* array;    int size;    int capacity; } BinaryHeap; BinaryHeap* createBinaryHeap(int capacity) {    BinaryHeap* heap = (BinaryHeap*)malloc(sizeof(BinaryHeap));    heap->array = (int*)malloc(capacity * sizeof(int));    heap->size = 0;    heap->capacity = capacity;    return heap; }void swap(int* a, int* b) {    int temp = *a;    *a = *b;    *b = temp; }void insert(BinaryHeap* heap, int value) {    if (heap->size >= heap->capacity) {        printf("Heap overflow, cannot insert.\n");        return;    }    int currentIndex = heap->size;    heap->array[currentIndex] = value;    while (currentIndex != 0 && heap->array[currentIndex] > heap->array[(currentIndex - 1) / 2]) {        swap(&(heap->array[currentIndex]), &(heap->array[(currentIndex - 1) / 2]));        currentIndex = (currentIndex - 1)


answered by: Hydra Master
Add a comment
Know the answer?
Add Answer to:
Write a C function for each of the following, must be between 10 - 20 lines,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need question 9-10 answered. Thank you Question 1 iShow the resulting binary search tree if...

    I need question 9-10 answered. Thank you Question 1 iShow the resulting binary search tree if we are to insert following elements into the tree in given order, [34, 12, 23, 27,31,9,11,45, 20, 37. i) Show the resulting balanced binary search tree if we are to insert following sorted elements into the tree, [9,12,21, 23, 29, 31, 34, 45, 48, 52, 55] iii What is the pre-order traversal of the balanced binary search tree? v) What is the post-order traversal...

  • Prob. 3. Given the following data 50 40 23 36 19 20 9 a) Is this...

    Prob. 3. Given the following data 50 40 23 36 19 20 9 a) Is this a max heap, draw the tree and check if this is a max heap. b) Illustrate how you would add a new data 46 to the existing maxheap. c) From the answer obtained in part b, illustrate how you would delete the data 40 d) Now illustrate heap sort with the existing data after step c. Give steps, and find runtime. Runtime|Explanation of Algorithm...

  • 1. Write a recursive function that returns the sum of all even integers in a LinkedBinaryTree. Yo...

    please explain each line of code! ( in python ) 1. Write a recursive function that returns the sum of all even integers in a LinkedBinaryTree. Your function should take one parameter, root node. You may assume that the tree only contains integers. You may not call any methods from the LinkedBinaryTree class. Specifically, you should traverse the tree in your function def binary tree even sum (root): Returns the sum of al1 even integers in the binary tree 2....

  • 1. Given the two binary trees below: 14 16 Write a method called swapSubtrees, which swaps all of...

    in java ..write all complete program from a- e 1. Given the two binary trees below: 14 16 Write a method called swapSubtrees, which swaps all of the left and right subtrees in the above binary trees. Add this method to the class BinaryTree and create a program to test this method for these 2 trees. Show the original trees and the resulting trees. Note: To test your algorithm, first create a binary search tree. Write a method called singleParent,...

  • Binary Tree Template Write your own version of a class template that will create a binary...

    Binary Tree Template Write your own version of a class template that will create a binary tree that can hold values of any data type. Demonstrate the class with a driver program. Place your binary tree template in it's own header file, Btree.h. Include methods for the following: inserting new values into the tree removing nodes from the tree searching the tree returning the number of nodes in the tree displaying the contents of the tree using preorder traversal Your...

  • Q8 - Construct a Binary Search Tree by inserting the following sequence of numbers. 5,6,3,2,10,4,1,7,9,8. Write...

    Q8 - Construct a Binary Search Tree by inserting the following sequence of numbers. 5,6,3,2,10,4,1,7,9,8. Write down the level ordered traversal sequence of the final tree after insert. Delete node 10, 8, and 6 step by step using in-order successor. Write down the level ordered traversal sequence after every delete. I want you to write down (1 level ordered traversal for the insert and 3 level-ordered traversals for the deletes). In total there should be 4 level-ordered traversal sequences in...

  • please do this lab in Java in given instructions by tomorrow morning. TkA CHRI - TREE...

    please do this lab in Java in given instructions by tomorrow morning. TkA CHRI - TREE UTH A HEAPOF PRESDNS CENETH CSC 236-Lab 6 (2 programs) trees 1. Given the two binary trees below: 14 18 16) Write a method called swapSubtrees, which swaps all of the left and right subtrees in the above binary trees. Add this method to the class BinaryTree and create a program to test this method for these 2 trees. Show the original trees and...

  • 1. In Lab 4, you developed a program to build a Max Heap, and then Heap...

    1. In Lab 4, you developed a program to build a Max Heap, and then Heap Sort. Update the program by adding two additional functions: (a) AddData(A, N, V) where V is the new value added. (b) Delete a data Delete by giving the index of the data position Make sure to display the array after calling each of the function. 2. Write a program to implement Binary Search Algorithm, which will return the index of the data searched (V)....

  • C++ Vectors and Binary Search Trees • Write a program that takes from the user n...

    C++ Vectors and Binary Search Trees • Write a program that takes from the user n integers and stores them a vector of int. Then, create a function insert After that takes first Value and second Value. This function searches for each occurrence of first Value in the vector and insert the second Value after it in the same vector. The first and second values are taken from the user. • Create another function that creates a Binary Search Tree...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT