Write down C++ code to create a complete binary Tree in which user can add any number of node/elements (Numeric). After Creating a complete binary tree , You need to calculate the product of the 2nd lowest level and find the smallest number in the binary tree as given in the example:
Product of Elements in 2nd last level (N-1)= 20
Smallest number in Binary Tree = 2
1
Expert's answer
2016-12-04T04:28:11-0500
#include <stdio.h> class BinaryTree { int* tree_array; //tree array, where nodes are from up to bottom from left to right int size; public: void getTreeFromInput() { scanf("%d",&size); tree_array = new int[size]; for (int i = 0; i < size; i++) scanf("%d", &tree_array[i]); } void printProduct() { if (size <= 1) { printf("tree has less than one level\n"); return; } int ans = 1; int temp = size; int depth = 0; while (temp > 0) { depth++; temp /= 2; } for (int i = (1<<depth-2); i < (1<<depth-1); i++) ans *= tree_array[i-1]; printf("%d\n",ans); } }; int main() { BinaryTree my_tree; my_tree.getTreeFromInput(); my_tree.printProduct(); return 0; }
Comments
Leave a comment