Question

in C++ Find the least common ancestor (LCA) of two nodes in a “binary search tree.”...

in C++

Find the least common ancestor (LCA) of two nodes in a “binary search tree.” Please read the key vector {500,300,600,550,700,750,200,150,250,350,800}. Pick up two random keys and show their LCA.  

note(also write the algorithm in steps. solution should have the screenshots of source code and output, code should be done in dev or codeblock so it can easily run on my computer)

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

CODE:

#include <iostream> #include <bits/stdc++.h> using namespace std; // Data structure to store a Binary Search Tree node struct

OUTPUT:

LCA of 200 and 800 is 500

CODE TO COPY:

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

// Data structure to store a Binary Search Tree node
struct Node {
   int data;
   Node *left, *right;
};

// Function to create a new BST node having given key
Node* newNode(int key)
{
   Node* node = new Node;
   node->data = key;
   node->left = node->right = nullptr;

   return node;
}

// Function to perform in-order traversal of the tree
void inorder(Node* root)
{
   if (root == nullptr)
       return;

   inorder(root->left);
   cout << root->data << " ";
   inorder(root->right);
}

// Recursive function to insert an key into BST
Node* insert(Node* root, int key)
{
   // if the root is null, create a new node an return it
   if (root == nullptr)
       return newNode(key);

   // if given key is less than the root node, recur for left subtree
   if (key < root->data)
       root->left = insert(root->left, key);

   // if given key is more than the root node, recur for right subtree
   else
       root->right = insert(root->right, key);

   return root;
}

// Iterative function to search a given key in root
bool search(Node *root, int key)
{
   // traverse the tree and search for the key
   while (root)
   {
       // if given key is less than the current node, go to left
       // subtree else go to right subtree

       if (key < root->data)
           root = root->left;
       else if (key > root->data)
           root = root->right;

       // if key is found return true
       else
           return true;
   }

   // we reach here if the key is not present in the BST
   return false;
}

// Recursive function to find Lowest Common Ancestor of given nodes
// x and y where both x and y are present in the Binary Search Tree
Node *LCARecursive(Node* root, int x, int y)
{
   // base case: empty tree
   if (root == nullptr)
       return nullptr;

   // if both x and y is smaller than root, LCA exists in left subtree
   if (root->data > max(x, y))
       return LCARecursive(root->left, x, y);

   // if both x and y is greater than root, LCA exists in right subtree
   else if (root->data < min(x, y))
       return LCARecursive(root->right, x, y);

   // if one key is greater (or equal) than root and one key is smaller
   // (or equal) than root, then the current node is LCA
   return root;
}

// Print Lowest Common Ancestor of two nodes in a BST
void LCA(Node* root, int x, int y)
{
   // return if tree is empty or either x or y is not present in the tree
   if(root == nullptr || !search(root, x) || !search(root, y))
       return;

   // lca stores lowest common ancestor of x and y
   Node* lca = LCARecursive(root, x, y);

   // if lowest common ancestor exists, print it
   if (lca != nullptr)
       cout << "LCA of "<<x<<" and "<<y<<" is " << lca->data << endl;
   else
       cout << "LCA do not exist\n";
}

int main()
{
   Node* root = nullptr;

   vector<int> vect{ 500,300,600,550,700,750,200,150,250,350,800};

    for (int x : vect)
        root = insert(root, x);
    int a=vect[rand()%11];
    int b=vect[rand()%11];
   LCA(root, a,b);

   return 0;
}

ALGORITHM:

LCA(root,x,y):

step 1:if root is null return null

step 2 :if root is greater than both x and y then LCA(root->left,x,y)

step 3:if root is lesser than both x and y then LCA(root->right,x,y)

step3:return root->value

Add a comment
Know the answer?
Add Answer to:
in C++ Find the least common ancestor (LCA) of two nodes in a “binary search tree.”...
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
  • A Binary Search Tree is a binary tree where nodes are ordered in the following way:...

    A Binary Search Tree is a binary tree where nodes are ordered in the following way: each node contains one key (also known as data) the keys in the left subtree are less than the key in its parent node the keys in the right subtree are greater than the key in its parent node duplicate keys are not allowed Create a Binary Search Tree inserting the following list of numbers in order from left to right. 10,          6,           4,            8,            18,          15,          21 Please type...

  • Question 4: Create a method for a Binary Search tree that finds the lowest common ancestor...

    Question 4: Create a method for a Binary Search tree that finds the lowest common ancestor of two nodes in a tree (nodesLCA). The two nodes are input by the user identified by their values. Discuss method's Big-O notation. Add proper and consistent documentation to identify code sections or lines to clearly identify its purpose. Illustrate the performance of the nodesLCA method. Excute the method on following pairs: (500, 271), (21, 203) and (53 , 991)

  • Binary Search Tree Part A: The code attached in this document is a sample code to demonstrate ins...

    Binary Search Tree Part A: The code attached in this document is a sample code to demonstrate insert operation in binary search tree. Please fill in the missing part for the insert method to make the program work. The expected output should be as follows. 20 30 40 50 60 70 80 Part B: Find Lowest Common Ancestor (LCA) of a Binary Search Tree. According to WikiPedia definition , The lowest common ancestor is defined between two nodes v and...

  • Suppose a binary search tree has multiple nodes containing the same key value, k. Let node...

    Suppose a binary search tree has multiple nodes containing the same key value, k. Let node p be the lowest common ancestor of such nodes. Then, the key of p must be also k. If this is true, provide an argument. Otherwise, provide a counterexample.

  • (C++ Psuedocode) A pair of nodes x, y in a (supposed) binary search tree violate the...

    (C++ Psuedocode) A pair of nodes x, y in a (supposed) binary search tree violate the BST property if x is an ancestor of y, and the corresponding values are “out of order”. Given a BST, find the number of pairs that violate the BST property.

  • A collection of nodes is arranged as a binary search tree ordered on the field INFO which contain...

    A collection of nodes is arranged as a binary search tree ordered on the field INFO which contains distinct positive integers for each of the nodes. In addition to INFO, LLINK and RLINK, each node has three other fields CLASS SUCC and PRED CLASS is an information field containing a single letter that denotes the class to which the node belongs (there being up to 26 classes). The nodes in each class are arranged as a doubly-linked circular list with...

  • (20 points) Suppose you are given a binary search tree T of n nodes (as discussed...

    (20 points) Suppose you are given a binary search tree T of n nodes (as discussed in class. each node v has v.left, v.right, and v.key). We assume that no two keys in T are equal. Given a value x, the rank operation rank() is to return the rank of x in T, which is defined to be one plus the number of keys of T smaller than 2. For example, if T has 3 keys smaller than r, then...

  • C++ (Using Binary Search Trees) other methods will result in downvote Implement the binary search tree...

    C++ (Using Binary Search Trees) other methods will result in downvote Implement the binary search tree methods (bst.cpp) for the binary search tree provided in the header file. Test your implementation with the included test. bst.h bst_test.cpp Note: Your implementation must correspond to declarations in the header file, and pass the test. Do not modify these two. I will compile your code against these. If the compilation fails, you will get down vote. bst.h #ifndef BINARY_SEARCH_TREE_H #define BINARY_SEARCH_TREE_H #include <string>...

  • 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...

  • Write a program to use a binary search tree to store a list of computer games....

    Write a program to use a binary search tree to store a list of computer games. Each node in the tree stores the title (string) of a computer game. Different games have different titles. Your program should display the following menu repeatedly: 1. Insert new game 2. Search for games          3. List games 4. quit Option 1 should read a game (title) and add the game into the tree.  Option 2 allows the user to enter a partial key...

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