DSA Quiz 3 Solution 26122020 035014pm
DSA Quiz 3 Solution 26122020 035014pm
Write a program to print only the leaf nodes of a tree. Your tree must have at least 15 nodes. You can
use the code from previous lecture to perform this task.
Code:
#include<iostream>
#include<conio.h>
using namespace std;
class Node
{
public:
int data;
Node* left;
Node* right;
};
class BT
{
private:
Node* root;
void insert(int val, Node* tree)
{
Node* n = newNode(val);
if (val <= tree->data)
{
if (tree->left == NULL)
tree->left = n;
else
insert(val, tree->left);
}
else
{
if (tree->right == NULL)
tree->right = n;
else
insert(val, tree->right);
}
}
void inorder(Node* tree)
{
if (tree != NULL)
{
inorder(tree->left);
cout << tree->data << " ";
inorder(tree->right);
}
}
public:
BT()
{
root = NULL;
}
Node* newNode(int val)
{
Node* n = new Node;
n->data = val;
n->left = NULL;
n->right = NULL;
return n;
}
void insert(int val)
{
if (root == NULL)
{
Node* n = newNode(val);
root = n;
}
else
insert(val, root);
}
void inorder()
{
inorder(root);
cout << endl;
}
void LeafNodes(Node* Root)
{
if (Root == NULL)
{
Root = root;
}
if (Root == NULL)
{
cout << "There is no Node in Tree...";
return;
}
if (Root->left == NULL && Root->right == NULL)
{
cout << Root->data << " ";
return;
}
if (Root->right)
LeafNodes(Root->right);
if (Root->left)
LeafNodes(Root->left);
}
};
int main()
{
BT bt;
Node* Root = NULL;
int arr[8];
for (int i = 0; i < 8; i++)
{
cout << "Enter the Values: ";
cin >> arr[i];
bt.insert(arr[i]);
}
cout << "\Inorder Form: ";
bt.inorder();
cout << "\nLeaf Nodes Are: ";
bt.LeafNodes(Root);
_getch();
return 0;
}
Output: