Write a Program to Find the Maximum Depth or Height of a Tree

Given a binary tree, find height of it. Height of empty tree is 0 and height of below tree is 2. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.

Example Tree

Recursively calculate height of left and right subtrees of a node and assign height to the node as max of the heights of two children plus 1. See below pseudo code and program for details. Algorithm:

 maxDepth()
1. If tree is empty then return 0
2. Else
     (a) Get the max depth of left subtree recursively  i.e., 
          call maxDepth( tree->left-subtree)
     (a) Get the max depth of right subtree recursively  i.e., 
          call maxDepth( tree->right-subtree)
     (c) Get the max of max depths of left and right 
          subtrees and add 1 to it for the current node.
         max_depth = max(max dept of left subtree,  
                             max depth of right subtree) 
                             + 1
     (d) Return max_depth

See the below diagram for more clarity about execution of the recursive function maxDepth() for above example tree.

Python3

Javascript

Output

Time Complexity: O(n) (Please see our post Tree Traversal for details)

Method 2: Another method to solve this problem is to do Level Order Traversal. While doing the level order traversal, while adding Nodes at each level to Queue, we have to add NULL Node so that whenever it is encountered, we can increment the value of variable and that level get counted.

**Implementation:**Python3

Time Complexity: O(n)

Space Complexity: O(n)

References: http://cslibrary.stanford.edu/110/BinaryTrees.html

Last updated