Finding the maximum depth of a binary tree
The maximum depth of a binary tree is the number of nodes from the root down to the furthest leaf node. In other words, it is the height of a binary tree.
Consider the binary tree illustrated below:
The maximum depth, or height, of this tree is 44; node 77 and node 88 are both four nodes away from the root.
Algorithm
The algorithm uses recursion to calculate the maximum height:
- Recursively calculate the height of the tree to the left of the root.
- Recursively calculate the height of the tree to the right of the root.
- Pick the larger height from the two answers and add one to it (to account for the root node).
Comments
Post a Comment