Write a Program to Find the Maximum Depth or Height of a Tree | C ++ program to find height of tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Compute the " maxDepth " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node . ; compute the depth of each subtree ; use the larger one ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; } ; int maxDepth ( node * node ) { if ( node == NULL ) return 0 ; else { int lDepth = maxDepth ( node -> left ) ; int rDepth = maxDepth ( node -> right ) ; if ( lDepth > rDepth ) return ( lDepth + 1 ) ; else return ( rDepth + 1 ) ; } } node * newNode ( int data ) { node * Node = new node ( ) ; Node -> data = data ; Node -> left = NULL ; Node -> right = NULL ; return ( Node ) ; } 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 ; }