Given a binary tree, find height of it. Height of empty tree is 0 and height of below tree is 3.
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.
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.
maxDepth('1') = max(maxDepth('2'), maxDepth('3')) + 1 = 2 + 1 / \ / \ / \ / \ / \ maxDepth('2') = 1 maxDepth('3') = 1 = max(maxDepth('4'), maxDepth('5')) + 1 = 1 + 1 = 2 / \ / \ / \ / \ / \ maxDepth('4') = 1 maxDepth('5') = 1
Height of tree is 3
Time Complexity: O(n) (Please see our post Tree Traversal for details)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Sum of nodes at maximum depth of a Binary Tree
- Sum of nodes at maximum depth of a Binary Tree | Set 2
- Minimum valued node having maximum depth in an N-ary Tree
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- Find Minimum Depth of a Binary Tree
- Calculate depth of a full Binary tree from Preorder
- Depth of the deepest odd level node in Binary Tree
- Depth of an N-Ary tree
- Replace node with depth in a binary tree
- Replace every node with depth in N-ary Generic Tree
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Find depth of the deepest odd level leaf node
- Iterative Method to find Height of Binary Tree
- Find Height of Binary Tree represented by Parent array
- Find height of a special binary tree whose leaf nodes are connected
- Write a program to Calculate Size of a tree | Recursion
- Write a program to Delete a Tree
- How to determine if a binary tree is height-balanced?
- Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in O(sqrt(height)) time)
- Print middle level of perfect binary tree without finding height