pls make a simple report 2 page and simple design #include<iostream> using names
ID: 638198 • Letter: P
Question
pls make a simple report 2 page and simple design
#include<iostream>
using namespace std;
//Defining Node
struct node{
int data;
struct node *left;
struct node *right;
};
//Function to insert a node in a BST
struct node* insert(struct node* node, int data)
{
if(node == NULL)
{
struct node* newnode = (struct node*) malloc (sizeof(struct node));
newnode->data = data;
newnode->left = NULL;
newnode->right = NULL;
node = newnode;
}
else
{
if(data <= node->data)
{
node->left = insert(node->left, data);
}
else
{
node->right = insert(node->right, data);
}
}
return (node);
}
//Finding common ancestor
struct node* commonancestor(struct node* root, int node1, int node2)
{
if(root == NULL) return NULL;
if(root->data < node1 && root->data < node2)
{
return commonancestor(root->right, node1, node2);
}
else if(root->data > node1 && root->data > node2)
{
return commonancestor(root->left, node1, node2);
}
else
{
return root;
}
}
//Distance between two given nodes
void distance(struct node* root, int node1, int node2)
{
if(root == NULL) return;
struct node* leftpath = root;
struct node* rightpath = root;
int countleft = 0, countright = 0;
while(leftpath != NULL)
{
if(leftpath->data > node1)
{
leftpath = leftpath->left;
countleft++;
}
else if(leftpath->data < node1)
{
leftpath = leftpath->right;
countleft++;
}
else
{
break;
}
}
while(rightpath != NULL)
{
if(rightpath->data > node2)
{
rightpath = rightpath->left;
countright++;
}
else if(rightpath->data < node2)
{
rightpath = rightpath->right;
countright++;
}
else
{
break;
}
}
cout<<"Shortest path between "<<node1<<"and "<<node2<<countleft+countright<<endl;
}
//Driver Function
int main(void)
{
struct node* root = NULL;
struct node* common = NULL;
root = insert(root, 9);
root = insert(root, 6);
root = insert(root, 15);
root = insert(root, 8);
root = insert(root, 4);
root = insert(root, 5);
root = insert(root, 1);
root = insert(root, 7);
root = insert(root, 13);
root = insert(root, 17);
root = insert(root, 11);
root = insert(root, 14);
root = insert(root, 19);
common = commonancestor(root, 2,9);
distance(common, 2, 9);
}
pls make a simple report 2 page and simple design
Explanation / Answer
Here you are going to binary search tree..in which binary tree is a tree where left child must less than root and right child greater than root..entire tree must follow this rule..
you are insertind nodes and placing accordingto rule that I mentioned above
And also checking common ancestor of two nodes given..you are checking whether root is null or not other wise you are returning ancestor
and similarly distance between like shortest path..node value as weights
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.