0
0
DSA Typescriptprogramming~30 mins

Why Trees Exist and What Linked Lists and Arrays Cannot Do in DSA Typescript - See It Work

Choose your learning style9 modes available
Why Trees Exist and What Linked Lists and Arrays Cannot Do
📖 Scenario: Imagine you are organizing a family reunion. You want to keep track of family members and their relationships, like parents and children. Using simple lists or arrays makes it hard to show these connections clearly. Trees help us organize such data naturally.
🎯 Goal: Build a simple tree structure in TypeScript to represent family members and their children. Understand why linked lists and arrays cannot easily show these parent-child relationships.
📋 What You'll Learn
Create a tree node structure with a name and children
Add children to a parent node
Traverse the tree to print family members and their children
Show why arrays or linked lists alone cannot represent this hierarchy
💡 Why This Matters
🌍 Real World
Trees are used to represent hierarchical data like family trees, company structures, file systems, and more.
💼 Career
Understanding trees helps in software development roles involving data organization, search algorithms, and UI component trees.
Progress0 / 4 steps
1
Create a Tree Node Interface
Create an interface called TreeNode with two properties: name of type string and children which is an array of TreeNode.
DSA Typescript
Hint

Think of each family member as a node with a name and a list of children nodes.

2
Create a Root Node with Children
Create a constant root of type TreeNode with name set to 'Grandparent' and children as an array containing two TreeNode objects with names 'Parent1' and 'Parent2', each having empty children arrays.
DSA Typescript
Hint

Start with one grandparent node and add two children nodes with empty children arrays.

3
Add a Child to One Parent
Add a child node with name 'Child1' and empty children array to the children array of the Parent1 node inside root.
DSA Typescript
Hint

Find the 'Parent1' node and add a new child node inside its children array.

4
Print the Tree Structure
Write a function printTree that takes a TreeNode and a level number (default 0). It prints the node's name with indentation based on level. Then it calls itself recursively for each child with level + 1. Finally, call printTree(root) to display the family tree.
DSA Typescript
Hint

Use indentation to show levels. Call the function recursively for children.