HomeAbout Me

Implement this BinaryTree

By Daniel Nguyen
Published in Javascript
April 13, 2025
1 min read

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);
}
}

Example usage:

// Constructing a binary tree
// 10
// / \
// 5 20
// / \
// 3 7
const 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

Tags

#Javascript

Share

Previous Article
List out the words that have a maximum number

Related Posts

How `this` behaves in JavaScript
April 24, 2025
1 min
© 2025, All Rights Reserved.
Powered By

Quick Links

About Me

Legal Stuff

Social Media