0
0
DSA Javascriptprogramming~30 mins

Height of Binary Tree in DSA Javascript - Build from Scratch

Choose your learning style9 modes available
Height of Binary Tree
📖 Scenario: You are working on a simple program to find the height of a family tree. Each person can have up to two children. The height tells us how many generations are in the family.
🎯 Goal: Build a binary tree representing a family and write code to find its height.
📋 What You'll Learn
Create a binary tree node class called TreeNode with value, left, and right properties
Create a binary tree with exactly 3 levels using TreeNode
Write a function called height that calculates the height of the binary tree
Print the height of the binary tree
💡 Why This Matters
🌍 Real World
Binary trees are used in many real-world applications like family trees, file systems, and decision-making processes.
💼 Career
Understanding tree structures and recursion is important for software development roles, especially in algorithms and data structure interviews.
Progress0 / 4 steps
1
Create TreeNode class and root node
Create a class called TreeNode with a constructor that takes value and sets left and right to null. Then create a root node called root with value 1.
DSA Javascript
Hint

Remember to set left and right to null inside the constructor.

2
Add children to root to form 3 levels
Add two children to root: root.left with value 2 and root.right with value 3. Then add one child to root.left: root.left.left with value 4.
DSA Javascript
Hint

Assign new TreeNode objects to root.left, root.right, and root.left.left.

3
Write function to find height of binary tree
Write a function called height that takes a node and returns 0 if the node is null. Otherwise, return 1 + Math.max(height(node.left), height(node.right)).
DSA Javascript
Hint

Use recursion to find the height of left and right subtrees, then add 1.

4
Print the height of the binary tree
Use console.log to print the height of the tree by calling height(root).
DSA Javascript
Hint

The height of this tree is 3 because it has 3 levels.