0
0
DSA Javascriptprogramming~30 mins

Diameter of Binary Tree in DSA Javascript - Build from Scratch

Choose your learning style9 modes available
Diameter of Binary Tree
📖 Scenario: You are working on a program that analyzes a family tree structure. Each person is represented as a node in a binary tree, where the left and right children represent descendants. You want to find the longest path between any two people in this family tree, which is called the diameter of the tree.
🎯 Goal: Build a JavaScript program that calculates the diameter of a binary tree. The diameter is the number of nodes on the longest path between any two nodes in the tree.
📋 What You'll Learn
Create a binary tree using JavaScript objects with val, left, and right properties.
Use a helper variable to track the maximum diameter found during traversal.
Write a recursive function to calculate the height of each subtree and update the diameter.
Print the final diameter value.
💡 Why This Matters
🌍 Real World
Finding the diameter of a tree structure helps in network design, family tree analysis, and understanding the longest communication path in hierarchical data.
💼 Career
This concept is useful for software engineers working with tree data structures, such as in databases, file systems, and network routing algorithms.
Progress0 / 4 steps
1
Create the binary tree structure
Create a binary tree by defining a variable root that represents the root node. The root node should have val 1, a left child with val 2, and a right child with val 3. The left child of node 2 should have val 4, and the right child of node 2 should have val 5.
DSA Javascript
Hint

Use nested objects to represent each node with val, left, and right properties.

2
Add a variable to track the diameter
Add a variable called maxDiameter and set it to 0. This will keep track of the longest path found so far.
DSA Javascript
Hint

This variable will be updated later when you calculate the diameter.

3
Write a recursive function to calculate height and update diameter
Write a function called height that takes a node node as input. If node is null, return 0. Otherwise, recursively find the height of the left subtree and the right subtree. Update maxDiameter with the sum of left and right heights if it is larger than the current maxDiameter. Return the height of the current node as 1 plus the maximum of left and right heights.
DSA Javascript
Hint

Use recursion to find the height of left and right children, then update maxDiameter.

4
Calculate and print the diameter
Call the height function with root as the argument to start the calculation. Then print the value of maxDiameter using console.log(maxDiameter).
DSA Javascript
Hint

Calling height(root) starts the recursive calculation. The diameter is printed last.