Question

In: Computer Science

Given an array of foods, create a binary search tree. Then, make a copy of that...

Given an array of foods, create a binary search tree. Then, make a copy of that BST and balance it. Language is C++. Vectors are not allowed.

The balance function definition: void balance(BST treeObj); and then when writing the function: void BST::balance(BST treeObj) where BST is a class. The function will be called in main like: originalTree.balance(balancedTree);

Solutions

Expert Solution

Source code:

#include <iostream>
#include<string.h>
using namespace std;
 
class Node{
public:
    Node* lchild;
    string data;
    Node* rchild;
};
 
class BST{
private:
    Node* root;
public:
    BST(){ root = nullptr; }
    Node* getRoot(){ return root; }
    void iInsert(string key);
    void Inorder(Node* p);
    Node* iSearch(string key);
    Node* rInsert(Node* p, string key);
    Node* rSearch(Node* p, string key);
    Node* Delete(Node* p, string key);
    int Height(Node* p);
    Node* InPre(Node* p);
    Node* InSucc(Node* p);
};
 
void BST::iInsert(string key) {
 
    Node* t = root;
    Node* p;
    Node* r;
 
    // root is empty
    if (root == nullptr){
        p = new Node;
        p->data = key;
        p->lchild = nullptr;
        p->rchild = nullptr;
        root = p;
        return;
    }
 
    while(t != nullptr){
        r = t;
        if (key < t->data){
            t = t->lchild;
        } else if (key > t->data){
            t = t->rchild;
        } else {
            return;
        }
    }
 
    // Now t points at NULL and r points at insert location
    p = new Node;
    p->data = key;
    p->lchild = nullptr;
    p->rchild = nullptr;
 
    if (key < r->data){
        r->lchild = p;
    } else {
        r->rchild = p;
    }
 
}
 
void BST::Inorder(Node* p) {
    if (p){
        Inorder(p->lchild);
        cout << p->data << ", " << flush;
        Inorder(p->rchild);
    }
}
 
Node* BST::iSearch(string key) {
    Node* t = root;
    while (t != nullptr){
        if (key == t->data){
            return t;
        } else if (key < t->data){
            t = t->lchild;
        } else {
            t = t->rchild;
        }
    }
    return nullptr;
}
 
Node* BST::rInsert(Node *p, string key) {
    Node* t;
    if (p == nullptr){
        t = new Node;
        t->data = key;
        t->lchild = nullptr;
        t->rchild = nullptr;
        return t;
    }
 
    if (key < p->data){
        p->lchild = rInsert(p->lchild, key);
    } else if (key > p->data){
        p->rchild = rInsert(p->rchild, key);
    }
    return p;  // key == p->data?
}
 
Node* BST::rSearch(Node *p, string key) {
    if (p == nullptr){
        return nullptr;
    }
 
    if (key == p->data){
        return p;
    } else if (key < p->data){
        return rSearch(p->lchild, key);
    } else {
        return rSearch(p->rchild, key);
    }
}
 
Node* BST::Delete(Node *p, string key) {
    Node* q;
 
    if (p == nullptr){
        return nullptr;
    }
 
    if (p->lchild == nullptr && p->rchild == nullptr){
        if (p == root){
            root = nullptr;
        }
        delete p;
        return nullptr;
    }
 
    if (key < p->data){
        p->lchild = Delete(p->lchild, key);
    } else if (key > p->data){
        p->rchild = Delete(p->rchild, key);
    } else {
        if (Height(p->lchild) > Height(p->rchild)){
            q = InPre(p->lchild);
            p->data = q->data;
            p->lchild = Delete(p->lchild, q->data);
        } else {
            q = InSucc(p->rchild);
            p->data = q->data;
            p->rchild = Delete(p->rchild, q->data);
        }
    }
    return p;
}
 
int BST::Height(Node *p) {
    int x;
    int y;
    if (p == nullptr){
        return 0;
    }
    x = Height(p->lchild);
    y = Height(p->rchild);
    return x > y ? x + 1 : y + 1;
}
 
Node* BST::InPre(Node *p) {
    while (p && p->rchild != nullptr){
        p = p->rchild;
    }
    return p;
}
 
Node* BST::InSucc(Node *p) {
    while (p && p->lchild != nullptr){
        p = p->lchild;
    }
    return p;
}
 
 
int main() {
 
    BST bst;
 
    // Iterative insert
    bst.iInsert("Mc Donald's");
    bst.iInsert("Subway");
    bst.iInsert("Mandi");
    bst.iInsert("Burger king");
    bst.iInsert("Wendy's");
 
    // Inorder traversal
    bst.Inorder(bst.getRoot());
    cout << endl;
 
    // Iterative search
    Node* temp = bst.iSearch(2);
    if (temp != nullptr){
        cout << temp->data << endl;
    } else {
        cout << "Element not found" << endl;
    }
 
    // Recursive search
    temp = bst.rSearch(bst.getRoot(), 20);
    if (temp != nullptr){
        cout << temp->data << endl;
    } else {
        cout << "Element not found" << endl;
    }
 
    // Recursive insert
    bst.rInsert(bst.getRoot(), 50);
    bst.rInsert(bst.getRoot(), 70);
    bst.rInsert(bst.getRoot(), 1);
    bst.Inorder(bst.getRoot());
    cout << "\n" << endl;
 
    // Inorder predecessor and inorder successor
    BST bs;
    bs.iInsert(5);
    bs.iInsert(2);
    bs.iInsert(8);
    bs.iInsert(7);
    bs.iInsert(9);
    bs.iInsert(1);
 
    temp = bs.InPre(bs.getRoot());
    cout << "InPre: " << temp->data << endl;
 
    temp = bs.InSucc(bs.getRoot());
    cout << "InSucc: " << temp->data << endl;
 
    bs.Inorder(bs.getRoot());
    cout << endl;
 
    // Delete
    bs.Delete(bs.getRoot(), 7);
    bs.Inorder(bs.getRoot());
    
    return 0;
}
Let me know if you have any doubts or if you need anything to change. 

If you are satisfied with the solution, please leave a +ve feedback : ) Let me know for any help with any other questions.

Thank You!
===========================================================================

Related Solutions

Binary Tree Create a binary search tree using the given numbers in the order they’re presented....
Binary Tree Create a binary search tree using the given numbers in the order they’re presented. State if the resulting tree is FULL and/or BALANCED. 37, 20, 18, 56, 40, 42, 12, 5, 6, 77, 20, 54
(C++) I need to Create a Copy function of a Binary Search Tree recursively providing these...
(C++) I need to Create a Copy function of a Binary Search Tree recursively providing these structure emplate <typename T> class Tree {    struct TreeNode    {        T mData;        TreeNode* mLeft = nullptr;        TreeNode* mRight = nullptr;        TreeNode* mParent = nullptr;        bool mIsDead = false;        TreeNode()        {        }        TreeNode(T tData) : TreeNode()        {            mData = tData;...
Prerequisite Knowledge Understand binary search tree structure Understand binary search tree operations Understand binary search tree...
Prerequisite Knowledge Understand binary search tree structure Understand binary search tree operations Understand binary search tree worst case and best case time. Learning Outcomes Describe AVL tree structure Trace and implement AVL tree operations Explain and prove AVL tree performance
Please make an Array-based implementation of a Binary Tree in Python based on the given file...
Please make an Array-based implementation of a Binary Tree in Python based on the given file below. Make sure to keep the Abstract Data File of the starter code below when building the Array-based implementation. Python Starter Code Given Below: class ArrayBinaryTree(BinaryTree): """Linked representation of a binary tree structure.""" # -------------------------- nested _Node class -------------------------- class _Node: def __init__(self, element, parent=None, left=None, right=None): # -------------------------- nested Position class -------------------------- class Position(BinaryTree.Position): """An abstraction representing the location of a single element."""...
​Define a tree. Distinguish between a tree and a binary tree. Distinguish between a binary tree and a binary search tree.
Define a tree. Distinguish between a tree and a binary tree. Distinguish between a binary tree and a binary search tree.
Make an Array implementation of a binary tree given the below class ArrayBinaryTree(BinaryTree): """Linked representation of...
Make an Array implementation of a binary tree given the below class ArrayBinaryTree(BinaryTree): """Linked representation of a binary tree structure.""" # -------------------------- nested _Node class -------------------------- class _Node: def __init__(self, element, parent=None, left=None, right=None): # -------------------------- nested Position class -------------------------- class Position(BinaryTree.Position): """An abstraction representing the location of a single element.""" def __init__(self, container, node): def element(self): def __eq__(self, other): # ------------------------------- utility methods ------------------------------- def _validate(self, p): """Return associated node, if position is valid.""" def _make_position(self, node): """Return Position...
Question 2: Create a method (sortTraversal) for a Binary Search Tree that prints out the Binary...
Question 2: Create a method (sortTraversal) for a Binary Search Tree that prints out the Binary Search Tree in ascending or deceasing order. The order type is an input to the method and can be "ascending" or "descending". The ascending input would return the node values of the tree beginning with the smallest and ending with the largest, descending returns the opposite. Discuss method's Big-O notation. Add proper and consistent documentation to identify code sections or lines to clearly identify...
PYTHON CODING Create a method (sortTraversal) for a Binary Search Tree that prints out the Binary...
PYTHON CODING Create a method (sortTraversal) for a Binary Search Tree that prints out the Binary Search Tree in ascending or deceasing order. The order type is an input to the method and can be "ascending" or "descending". The ascending input would return the node values of the tree beginning with the smallest and ending with the largest, descending returns the opposite. Discuss method's Big-O notation. Add proper and consistent documentation to identify code sections or lines to clearly identify...
C++ Instantiate a binary search tree object and create such tree using elements of the sequence...
C++ Instantiate a binary search tree object and create such tree using elements of the sequence 8,3,10, 1,6,9, 14, 4,7, 13 with 8 as root of the tree. Find maximum and minimum elements of the tree, successor(10) and predecessor(13), print the inorder, postorder and preorder traversal of the tree.
In this assignment you will create a Binary Search Tree to storeand retrieve objects of...
In this assignment you will create a Binary Search Tree to store and retrieve objects of type ItemType. The purpose of this assignment is for you to become familiar with basic tree operations, and understand the efficiency of trees compared to previously studied data structures. Binary Tree nodes have only two children, left and right. Nodes are compared based on their Key instance variable, which in this assignment is of type ItemType. All elements in the left subtree of a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT