Find the maximun depth or height of a binary tree
Binary Trees
JavaScript
Problem:
Given a binary tree, find the maximun depth or height of a binary tree. The height of the tree is the number of vertices in the tree from the root to the deepest node.
Algorithm:
- If the tree is empty, return
0
(indicating no height). - Traverse the left and right subtrees, recursively calculating the height of each.
- Recursively calculate the height of the left subtree.
- Recursively calculate the height of the right subtree.
- Determine the maximum height between the left and right subtrees, and add 1 to account for the current node’s height.
This approach calculates the height by recursively determining the heights of the left and right subtrees and returning the greater of the two, plus one for the current node.
Solution & Visualize:
The animation/visualization below demonstrates how the algorithm works.
Result
Code
Input:
The tree nodes should only contain the numbers or `null` followed by comma
Output:
solution.js
binary-tree.js