Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created HeightOfBinaryTree.cpp #433

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions HeightOfBinaryTree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#include<iostream>
using namespace std;

// structure of node
struct Node
{
Node *left; // Pointer to left sub-tree
int element; // Value
Node *right; // Pointer to right sub-tree
Node(int theElement,Node *theLeft,Node *theRight)
{
element = theElement;
left = theLeft;
right = theRight;
}
};

int height(Node *root)
{
int h = 0;
if(root != NULL)
{
int lHeight = height(root->left);
int rHeight = height(root->right);
int maxHeight = max(lHeight,rHeight);
h = maxHeight + 1;
}
return h;
}

int main()
{
// creating a binary tree with 5 nodes
Node *n1,*n2,*n3,*n4,*n5;
n1 = new Node(5,NULL,NULL);
n2 = new Node(7,NULL,NULL);
n3 = new Node(6,n1,n2);
n4 = new Node(9,NULL,NULL);
n5 = new Node(3,n3,n4);

cout << "Height of the tree is " << height(n5) << endl;
return 0;
}