Explain and diagrammatically illustrate the function int main() in the below program
Explain and diagrammatically illustrate the function int main() in the below program.
#include <iostream>
using namespace std;
struct node
{
char data;
struct node *left;
struct node *right;
};
struct node* newNode(char data)
{
struct node *node = new struct node();
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
// find and display father node with its child nodes
void Childs(node *root,char D)
{
if(root==NULL)
{
return;
}
if(root->data==D)
{
if(root->left!=NULL&&root->right!=NULL)
{
cout<<root->data<<" is the father of : ";
cout<<root->left->data<<" and "<<root->right->data<<endl;
return;
}
else if(root->left==NULL&&root->right!=NULL)
{
cout<<root->data<<" has only one child i.e. : ";
cout<<root->right->data<<endl;
return;
}
else if(root->left!=NULL&&root->right==NULL)
{
cout<<root->data<<" has only one child i.e. : ";
cout<<root->left->data<<endl;
}
else
{
cout<<root->data<<" Has No Child\n";
return;
}
}
Childs(root->left,D);
Childs(root->right,D);
}
// Display all the tree nodes in one line
void display(node* r)
{
if(r==NULL)
{
return;
}
else
{
display(r->left);
cout<<r->data<<" ";
display(r->right);
}
}
// Display all the tree nodes in 2D form
int COUNT=10;
void Print_2D(node *Root, int space)
{
if (Root == NULL)
{
return;
}
else
{
// Increment of Space between levels
space +=COUNT;
// First Process right child
Print_2D(Root->right, space);
cout<<"\n";
// Adding the spaces
for(int i=COUNT; i<space; i++)
{
cout<<" ";
}
//Display Current Root DATA
cout<<Root->data<<"\n";
// Process left child
Print_2D(Root->left, space);
}
}
int main()
{
struct node *rootNode = newNode('A');
rootNode->left = newNode('K');
rootNode->right = newNode('L');
rootNode->left->left = newNode('P');
rootNode->left->right = newNode('Q');
rootNode->right->left = newNode('B');
rootNode->right->right = newNode('C');
rootNode->left->left->left = newNode('J');
rootNode->right->left->left = newNode('X');
rootNode->right->left->right = newNode('Y');
rootNode->right->right->left = newNode('Z');
display(rootNode);
cout<<endl<<endl;
Print_2D(rootNode,0);
cout<<endl<<endl;
Childs(rootNode,'A');
Childs(rootNode,'K');
Childs(rootNode,'L');
Childs(rootNode,'P');
Childs(rootNode,'Q');
Childs(rootNode,'B');
Childs(rootNode,'C');
cout<<endl<<endl;
return 0;
}
Step by step
Solved in 2 steps with 1 images