Question

In: Computer Science

Implement a function to remove a leaf node from a binary search tree. Using the following...

Implement a function to remove a leaf node from a binary search tree. Using the following class and function definition:

class BTNode {
public:
   int item;
   BTNode *left;
   BTNode *right;
   BTNode(int i, BTNode *l=nullptr, BTNode *r=nullptr):item(i),left(l),right(r){}
};

BTNode *root = nullptr;

BTNode * remove_leaf(int item, bool &removed) {
     // implement
}

The remove function will return the node with the item if it's present in the tree. If the node is a leaf node and is removed by the function, it sets removed=true. Otherwise, if not removed because it is not a leaf node, it sets removed=false. In either case, the function should return a pointer to the node if present in the tree; if not present, return nullptr.

#include <iostream>

class BTNode {
public:
int item;
BTNode *left;
BTNode *right;
BTNode(int i, BTNode *l=nullptr, BTNode *r=nullptr):item(i),left(l),right(r){}
};

BTNode *root = nullptr;

BTNode * remove_leaf(int item, bool &removed) {

removed = false;   
return nullptr;
}

int main()
{
root = new BTNode(50, new BTNode(25), new BTNode(100));
bool r=false;

BTNode *tmp50 = remove_leaf(50,r);
if (tmp50 == nullptr || r == true) {
std::cout << "Should not have removed node 50! It has a child node." << std::endl;
} else if (!r) {
std::cout << "Correctly chose not to remove node 50." << std::endl;
}

BTNode *tmp100 = remove_leaf(100,r);
if (tmp100 == nullptr || r == false) {
std::cout << "Should have removed node 100! It is a leaf node." << std::endl;
} else if (r) {
std::cout << "Correctly chose to remove node 100." << std::endl;
}

BTNode *tmp25 = remove_leaf(25,r);
if (tmp25 == nullptr || r == false) {
std::cout << "Should have removed node 25! It is a leaf node." << std::endl;
} else if (r) {
std::cout << "Correctly chose to remove node 25." << std::endl;
}

tmp50 = remove_leaf(50,r);
if (tmp50 == nullptr || r == false) {
std::cout << "Should have removed node 50! It is a leaf node." << std::endl;
} else if (r) {
std::cout << "Correctly chose to remove node 50." << std::endl;
}
if (root!=nullptr) {
std::cout << "root should be nullptr now, but it isn't!" << std::endl;
} else {
std::cout << "Correctly set root to nullptr." << std::endl;
}

return 0;
}

Solutions

Expert Solution

#include <iostream>
using namespace std;

class BTNode
{
public:
    int item;
    BTNode *left;
    BTNode *right;
    BTNode(int i, BTNode *l = nullptr, BTNode *r = nullptr) : item(i), left(l), right(r) {}
};

BTNode *root = nullptr;

BTNode *remove_leaf(int item, bool &removed)
{
    BTNode *current = root, *prev = nullptr;

    if (root == nullptr)
    {
        removed = false;
        return nullptr;
    }

    if (root->item == item)
    {
        if (root->left == nullptr && root->right == nullptr)
        {
            removed = true;
            root = nullptr;
        }
        else
        {
            removed = false;
        }
        return current;
    }
    while (current != nullptr && current->item != item)
    {
        prev = current;
        if (current->item < item)
            current = current->right;
        else if (current->item > item)
            current = current->left;
    }

    if (current == nullptr)
    {
        removed = false;
        return nullptr;
    }
    else
    {
        if (current->left == nullptr && current->right == nullptr)
        {
            removed = true;
            if (prev->left->item == item)
                prev->left = nullptr;
            else
                prev->right = nullptr;
        }
        else
        {
            removed = false;
        }
        return current;
    }
}


Related Solutions

Implement a function to find a node in a binary search tree. Using the following class...
Implement a function to find a node in a binary search tree. Using the following class and function definition. If a node with a matching value is found, return a pointer to it. If no match is found, return nullptr. #include <iostream> class BTNode { public: int item; BTNode *left; BTNode *right; BTNode(int i, BTNode *l=nullptr, BTNode *r=nullptr):item(i),left(l),right(r){} }; BTNode *root = nullptr; BTNode *find(int item) { //implement code here return nullptr; } int main() {    root = new...
Consider the following type of binary trees: data Tree a = Leaf a | Node (Tree...
Consider the following type of binary trees: data Tree a = Leaf a | Node (Tree a) (Tree a) A tree is balanced if the number of leaves in the left and right subtree of every node differ by at most one. Write a Haskell function balanced that returns whether a tree is balanced or not. balanced :: Tree a -> Bool
Lab 5: Binary Search Tree Implement operations for a Binary Search Tree class starting from the...
Lab 5: Binary Search Tree Implement operations for a Binary Search Tree class starting from the template provided under the PolyLearn assignment, using the class TreeNode that is also provided. You may (should) implement helper methods that make your code easier to write, read, and understand. You will also need to write test cases of your own as you develop the methods. You may use iterative and/or recursive functions in your implementation. The following starter files are available . •...
PYTHON CODING Using the structural node and methods discussed in Binary Search Tree below # Binary...
PYTHON CODING Using the structural node and methods discussed in Binary Search Tree below # Binary Tree Node structure class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None class BSTree(): def __init__(self, rootdata): self.root = Node(rootdata)    def insert(self, data, cur_node): if data < cur_node.data: if cur_node.left == None: cur_node.left = Node(data) else: self.insert(data, cur_node.left)    elif data > cur_node.data: if cur_node.right == None: cur_node.right = Node(data) else:...
I am trying to implement a search function for a binary search tree. I am trying...
I am trying to implement a search function for a binary search tree. I am trying to get the output to print each element preceding the the target of the search. For example, in the code when I search for 19, the output should be "5-8-9-18-20-19" Please only modify the search function and also please walk me through what I did wrong. I am trying to figure this out. Here is my code: #include<iostream> using namespace std; class node {...
Question - 1 Using the structural node and methods discussed in Binary Search Tree lectures, create...
Question - 1 Using the structural node and methods discussed in Binary Search Tree lectures, create a method for the Binary Search Tree that takes an unsorted input list and constructs a Binary Search Tree based on its values. Any duplicate value will only appear once on the tree. This method outputs a Binary Search Tree structure (not an enumeration of the tree). Discuss method's Big-O notation. Add proper and consistent documentation to identify code sections or lines to clearly...
You are given a reference to the root node of a binary search tree, that implements...
You are given a reference to the root node of a binary search tree, that implements a dictionary data structure. Please print all the elements in depths 500 through 510, all in sorted order. A node in a binary search tree is at depth x, if it takes x hops to get from the root. So the root is at depth 0, the children of the root are at depth 1, and so on. The class TreeNode defines a single...
I was trying to implement a simple binary search tree using this given class of bst...
I was trying to implement a simple binary search tree using this given class of bst in c++ public: BST(); ~BST(); void insertKey(int newKey); bool hasKey(int searchKey); std::vector<int> inOrder(); int getHeight(); however; i am still required to use another class for the nodes as a pointer and i need to manage memory leak. in main we should ask for the numbers we need to insert in the binary search tree and also let the user end it with a letter...
In java, create a binary search tree (without using additional libraries) of stacks where each node...
In java, create a binary search tree (without using additional libraries) of stacks where each node contains a key and a stack. In this binary search tree, when adding a new element to the tree it is inserted based off of its key value; if that key value already exist then the element is pushed into the stack at that location, if the key value does not exist a node element is added to the tree to reflect that key,...
(+5) Level of a node in a binary tree is distance from root to that node....
(+5) Level of a node in a binary tree is distance from root to that node. For example, level of root is 0 and levels of left and right children of the root are 1. Level      Max number of nodes 1 2 4 8 16 32 64 ..      … n       ?? The maximum number of nodes on level n of a binary tree is : A          2^(n-1)                         B          2^n C          2^(n+1)                       D            2^[(n+1)//2] In the above answers, the operator...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT