Member-only story
Coding Interview Prep: Finding the Maximum Depth of Binary Tree with JavaScript Solution
Code
var maxDepth = function(root) {
if (!root){
return 0;
}
let leftSubHeigth = maxDepth(root.left);
let rightSubHeight = maxDepth(root.right);
return Math.max(leftSubHeigth, rightSubHeight) + 1;
};
Explanation
A binary search tree is a data structure used in Computer Science for organizing and storing data in a sorted manner. Each node in a Binary Search Tree has at most two most children, a a left child and a right child. The left child is less than the parent node. The right child contains values greater than the parent node.
This hierarchical structure allows for efficient searching, insertion and deletion operations on the data stored in the tree.
Given a binary tree, the task is to find the height of the tree. The height of the tree is the number of vertices in the tree from the root to the deepest node.
The height of an empty tree is 0 and the height of a tree with a single node is 1.
To find the height of the tree, we will recursively calculate the height of the left and the right subtrees of a node and assign height to the node as max of heights of 2 children plus 1.