Recursive Approach
If root is null , return height of binary tree zero. Recursively calculate the height of the left subtree by calling function with the left child of the root. Recursively calculate the height of the right subtree by calling function with the right child of the root. Return the maximum of the heights of left and right subtrees plus one (for root node).
Example: To demonstrate how to find height of Binary tree using Recursive approach
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
// recursive approach
function heightOfBinaryTree(root) {
if (root === null) {
return 0;
}
const leftHeight = heightOfBinaryTree(root.left);
const rightHeight = heightOfBinaryTree(root.right);
return Math
.max(leftHeight, rightHeight) + 1;
}
const root = new TreeNode(11);
root.left = new TreeNode(12);
root.right = new TreeNode(13);
root.left.left = new TreeNode(14);
root.left.right = new TreeNode(15);
console.log(" height of binary tree using recursive approach is ",
heightOfBinaryTree(root));
Output
height of binary tree using recursive approach is 3
Time Complexity : O(n)
Space Complexity : O(n)
Height of Binary Tree using JavaScript
The height of a binary tree can be defined as the maximum depth or length of the longest path from the root node to any leaf node. Below is an example to illustrate the height of the binary tree.
There are several approaches to find height of Binary tree using JavaScript which are as follows:
Table of Content
- Iterative Approach
- Recursive Approach
Contact Us