In: Computer Science
I have a sequence of natural numbers. How can I get the height of the resulting tree/ c++(send code)
Hello, Student
You can I get the height of the resulting tree using this c++ program.
Please do not forget to hit that like or thumbs-up button.
TreeHeight.cpp
#include<iostream>
#include <stdlib.h>
using namespace std;
typedef struct Node Node;
struct Node {
int number;
// left and right children
Node* left, *right;
};
Node* make_tree(int data) {
Node* root = (Node*) malloc (sizeof(Node));
root->left = root->right = NULL;
root->number = data;
return root;
}
Node* make_node(int data) {
// Creates a new node
Node* node = (Node*) malloc (sizeof(Node));
node->number = data;
node->left = node->right = NULL;
return node;
}
void release_tree(Node* root) {
Node* temp = root;
if (!temp)
return;
release_tree(temp->left);
release_tree(temp->right);
if (!temp->left && !temp->right) {
free(temp);
return;
}
}
int get_height(Node* root) {
//found the height of whole tree
if (!root)
return 0;
else {
int left_height = get_height(root->left);
int right_height = get_height(root->right);
if (left_height >= right_height)
return left_height + 1;
else
return right_height + 1;
}
}
int main() {
// root node
Node* root = make_tree(50);
// Insert nodes or natural numbers on tree
root->left = make_node(60);
root->right = make_node(70);
root->left->left = make_node(80);
root->left->right = make_node(90);
// calculating Height of the tree
int height = get_height(root);
cout<<"Height of the Resulting tree is:"<<height<<endl;
// Making tree free from root
release_tree(root);
return 0;
}
Output :- Height of the Resulting tree is: 3
Output Screenshot:-
Note :- You can chage node values or your sequence of natural numbers. to get desired height of tree using make_node function in Int main().
Again, Please like my work, it really motivates me>3 (I hope you will do that?)