0
0
DSA Javascriptprogramming~30 mins

Tree Terminology Root Leaf Height Depth Level in DSA Javascript - Build from Scratch

Choose your learning style9 modes available
Understanding Tree Terminology: Root, Leaf, Height, Depth, Level
📖 Scenario: Imagine you are organizing a family tree. Each person is connected to their parents and children, forming a tree structure. To understand this tree better, you need to identify the root (oldest ancestor), leaves (family members with no children), and calculate the height, depth, and level of each member.
🎯 Goal: You will create a simple tree structure in JavaScript and write code to identify the root, leaves, and calculate height, depth, and level for each node.
📋 What You'll Learn
Create a tree object with nodes representing family members
Identify the root node
Identify leaf nodes
Calculate the height of the tree
Calculate the depth and level of each node
Print the results clearly
💡 Why This Matters
🌍 Real World
Trees are used in family trees, file systems, organizational charts, and many other hierarchical data representations.
💼 Career
Understanding tree terminology and traversal is essential for software developers working with data structures, databases, and algorithms.
Progress0 / 4 steps
1
Create the Tree Structure
Create a variable called familyTree representing this tree structure as nested objects: John is the root with children Mary and David. Mary has children Anna and James. David has no children.
DSA Javascript
Hint

Use nested objects with name and children arrays to represent the tree.

2
Identify Root and Leaf Nodes
Create a variable called root and set it to familyTree. Then create a function called findLeaves that takes a node and returns an array of names of all leaf nodes (nodes with empty children arrays).
DSA Javascript
Hint

Root is the top node. Leaves have no children. Use recursion to find leaves.

3
Calculate Height, Depth, and Level
Create a function called calculateHeight that returns the height of the tree starting from a given node. Then create a function called assignDepthAndLevel that takes a node and a depth number (start with 0) and adds depth and level properties to each node. Level is depth + 1.
DSA Javascript
Hint

Height is longest path to leaf. Depth starts at 0 for root. Level is depth + 1.

4
Print Tree Information
Call assignDepthAndLevel on root. Then print the root name, the array of leaf names from findLeaves(root), and the height of the tree from calculateHeight(root). Finally, print each node's name with its depth and level using a function printNodeInfo that traverses the tree.
DSA Javascript
Hint

Use console.log to print the root, leaves, height, and each node's depth and level.