From e9ef0f5db18f1f80aaffc5ccc821850a074dc543 Mon Sep 17 00:00:00 2001 From: Hemant Suteri <77913443+hemantsuteri@users.noreply.github.com> Date: Wed, 26 Oct 2022 12:29:53 +0530 Subject: [PATCH] Created HeightOfBinaryTree.cpp --- HeightOfBinaryTree.cpp | 43 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 HeightOfBinaryTree.cpp diff --git a/HeightOfBinaryTree.cpp b/HeightOfBinaryTree.cpp new file mode 100644 index 0000000..b0f6c3e --- /dev/null +++ b/HeightOfBinaryTree.cpp @@ -0,0 +1,43 @@ +#include +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; +}