How `this` behaves in JavaScript
April 24, 2025
1 min
Given the BinaryTree class with below structure.
Each Node will have a left Node, a right Node and a data.
Please Implement this BinaryTree class with method getMaxDepth() to calculate the highest depth of the binary tree.
Sure! Here’s the equivalent implementation of the BinaryTree
class with the getMaxDepth()
method in JavaScript:
class Node {constructor(data) {this.data = data;this.left = null;this.right = null;}}class BinaryTree {constructor(root = null) {this.root = root;}getMaxDepth() {const calculateDepth = (node) => {if (node === null) return 0;const leftDepth = calculateDepth(node.left);const rightDepth = calculateDepth(node.right);return Math.max(leftDepth, rightDepth) + 1;};return calculateDepth(this.root);}}
// Constructing a binary tree// 10// / \// 5 20// / \// 3 7const root = new Node(10);root.left = new Node(5);root.right = new Node(20);root.left.left = new Node(3);root.left.right = new Node(7);const tree = new BinaryTree(root);console.log(tree.getMaxDepth()); // Output: 3
Quick Links
Legal Stuff
Social Media