Here You can download CS301 Assignment No. 2 Solution & Discussion for Fall 2016.
CS301 Assignment No. 2 Solution
#include <stdio.h>
#include <iostream>
using namespace std;
struct Node
{
int val;
struct Node *left, *right;
};
Node *newNode(int data)
{
Node *temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to find deepest leaf node.
// lvl: level of current node.
// maxlvl: pointer to the deepest left leaf node found so far
// isLeft: A bool indicate that this node is left child of its parent
// resPtr: Pointer to the result
void deepestLeftLeafUtil(Node *root, int lvl, int *maxlvl,
bool isLeft, Node **resPtr)
{
// Base case
if (root == NULL)
return;
// Update result if this node is left leaf and its level is more
// than the maxl level of the current result
if (isLeft && !root->left && !root->right && lvl > *maxlvl)
{
*resPtr = root;
*maxlvl = lvl;
return;
}
// Recur for left and right subtrees
deepestLeftLeafUtil(root->left, lvl+1, maxlvl, true, resPtr);
deepestLeftLeafUtil(root->right, lvl+1, maxlvl, false, resPtr);
}
// A wrapper over deepestLeftLeafUtil().
Node* deepestLeftLeaf(Node *root)
{
int maxlevel = 0;
Node *result = NULL;
deepestLeftLeafUtil(root, 0, &maxlevel, false, &result);
return result;
}
Node* insert(Node* node, int val)
{
/* 1. If the tree is empty, return a new,
single node */
if (node == NULL)
return(newNode(val));
else
{
/* 2. Otherwise, recur down the tree */
if (val <= node->val)
node->left = insert(node->left, val);
else
node->right = insert(node->right, val);
/* return the (unchanged) node pointer */
return node;
}
}
int minValue(Node* node) {
Node* current = node;
/* loop down to find the leftmost leaf */
while (current->left != NULL) {
current = current->left;
}
return(current->val);
}
// Driver program to test above function
int main()
{
int a, b, c, d, e, f, g, h, i, j;
cout"Enter 10 Numbers in Tree:\n";
cin>>a>>b>>c>>d>>e>>f>>g>>h>>i>>j;
Node* root = newNode(a);
root->left = newNode(b);
root->right = newNode(c);
root->left->left = newNode(d);
root->right->left = newNode(e);
root->right->right = newNode(f);
root->right->left->right = newNode(g);
root->right->right->right = newNode(h);
root->right->left->right->left = newNode(i);
root->right->right->right->right = newNode(j);
root = insert(root, a);
insert(root, b);
insert(root, c);
insert(root, d);
insert(root, e);
insert(root, f);
insert(root, g);
insert(root, h);
insert(root, i);
insert(root, j);
Node *result = deepestLeftLeaf(root);
if (result){
cout "Product of 2nd lowest level of a binary tree is: " result->val * result->val;
}
else{
cout "There is no left leaf in the given tree";
}
printf("\nMinimum value in BST is %d", minValue(root));
return 0;
}