From 471b75ff776b4aeffa755a6232d19ec16b741994 Mon Sep 17 00:00:00 2001 From: Shalini-16 <73022957+Shalini-16@users.noreply.github.com> Date: Sun, 3 Oct 2021 16:00:45 +0530 Subject: [PATCH] Create MaxDepth_of_binary_tree.cpp --- MaxDepth_of_binary_tree.cpp | 62 +++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 MaxDepth_of_binary_tree.cpp diff --git a/MaxDepth_of_binary_tree.cpp b/MaxDepth_of_binary_tree.cpp new file mode 100644 index 0000000..8eb54c8 --- /dev/null +++ b/MaxDepth_of_binary_tree.cpp @@ -0,0 +1,62 @@ +// C++ program to find height of tree +#include +using namespace std; + + +/* A binary tree node has data, pointer to left child +and a pointer to right child */ +class node +{ + public: + int data; + node* left; + node* right; +}; + +/* Compute the "maxDepth" of a tree -- the number of + nodes along the longest path from the root node + down to the farthest leaf node.*/ +int maxDepth(node* node) +{ + if (node == NULL) + return 0; + else + { + /* compute the depth of each subtree */ + int lDepth = maxDepth(node->left); + int rDepth = maxDepth(node->right); + + /* use the larger one */ + if (lDepth > rDepth) + return(lDepth + 1); + else return(rDepth + 1); + } +} + +/* Helper function that allocates a new node with the +given data and NULL left and right pointers. */ +node* newNode(int data) +{ + node* Node = new node(); + Node->data = data; + Node->left = NULL; + Node->right = NULL; + + return(Node); +} + +// Driver code +int main() +{ + node *root = newNode(1); + + root->left = newNode(2); + root->right = newNode(3); + root->left->left = newNode(4); + root->left->right = newNode(5); + + cout << "Height of tree is " << maxDepth(root); + return 0; +} + +//Time Complexity O(n).