0
0
DSA Typescriptprogramming~30 mins

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

Choose your learning style9 modes available
Tree Terminology Root Leaf Height Depth Level
📖 Scenario: Imagine you are organizing a family tree. Each person is a node. You want to understand basic terms like root (oldest ancestor), leaf (person with no children), height (longest path to a leaf), depth (distance from root), and level (depth + 1).
🎯 Goal: You will create a simple tree structure in TypeScript and write code to identify the root, leaves, calculate height, depth, and level of nodes.
📋 What You'll Learn
Create a tree with exact nodes and connections
Define a variable for the root node
Write a function to find all leaf nodes
Write a function to calculate height of the tree
Write a function to calculate depth of a given node
Print the root, leaves, height, and depth of a specific node
💡 Why This Matters
🌍 Real World
Trees are used in family trees, file systems, organization charts, and many hierarchical data representations.
💼 Career
Understanding tree terminology and traversal is essential for software developers working with data structures, databases, and UI components.
Progress0 / 4 steps
1
Create the Tree Structure
Create a TypeScript interface called TreeNode with properties value: string and children: TreeNode[]. Then create a tree variable called familyTree with this exact structure: value: 'Grandparent', children: two nodes with values 'Parent1' and 'Parent2'. 'Parent1' has one child 'Child1', and 'Parent2' has two children 'Child2' and 'Child3'. All children arrays must be exact.
DSA Typescript
Hint

Define the interface first, then create the familyTree object with nested children arrays exactly as described.

2
Define the Root Node Variable
Create a constant variable called root and assign it the familyTree object.
DSA Typescript
Hint

Just assign familyTree to a new constant called root.

3
Find All Leaf Nodes
Write a function called findLeaves that takes a TreeNode parameter called node and returns an array of strings with the values of all leaf nodes (nodes with empty children). Use recursion to explore children.
DSA Typescript
Hint

Check if the node has no children, then return its value in an array. Otherwise, call findLeaves recursively on each child and combine results.

4
Calculate Height, Depth and Print Results
Write a function called height that takes a TreeNode and returns the height (max distance to a leaf). Write a function called depth that takes root, a TreeNode target, and current depth number, and returns the depth of the target node. Then print the root value, the array of leaves from findLeaves(root), the height of the tree, and the depth of the node with value 'Child3'.
DSA Typescript
Hint

Height is 0 for leaf nodes, otherwise 1 + max height of children. Depth counts steps from root to target. Use recursion for both. Print results exactly as shown.