0
0
DSA Typescriptprogramming~30 mins

Tree Traversal Preorder Root Left Right in DSA Typescript - Build from Scratch

Choose your learning style9 modes available
Tree Traversal Preorder Root Left Right
📖 Scenario: You are working with a simple family tree where each person can have up to two children. You want to visit each person starting from the oldest ancestor, then their left child, then their right child.
🎯 Goal: Build a program that creates a tree structure and prints the names of people in preorder traversal order: root first, then left child, then right child.
📋 What You'll Learn
Create a tree node class with name, left, and right properties
Create a tree with exactly three nodes: "Grandparent", "Parent", and "Child"
Write a preorder traversal function called preorderTraversal that visits nodes in root-left-right order
Print the names of the nodes in preorder traversal separated by spaces
💡 Why This Matters
🌍 Real World
Tree traversal is used in many real-world applications like file system navigation, organization charts, and parsing expressions.
💼 Career
Understanding tree traversal is essential for software developers working with hierarchical data, databases, and algorithms.
Progress0 / 4 steps
1
Create TreeNode class and build the tree
Create a class called TreeNode with a constructor that takes a name string and sets left and right to null. Then create three nodes: grandparent with name "Grandparent", parent with name "Parent", and child with name "Child". Connect grandparent.left to parent and parent.left to child.
DSA Typescript
Hint

Define the TreeNode class with name, left, and right. Then create the three nodes and link them as described.

2
Create a helper array to store traversal result
Create an empty array called result of type string[] to store the names of nodes during traversal.
DSA Typescript
Hint

Just create an empty array named result to hold the names as strings.

3
Write preorder traversal function
Write a function called preorderTraversal that takes a node of type TreeNode | null. If node is not null, push node.name to result, then recursively call preorderTraversal on node.left and node.right.
DSA Typescript
Hint

Use a function that checks if the node is not null, then adds the name to result, then calls itself on left and right children.

4
Run traversal and print result
Call preorderTraversal with grandparent as argument. Then print the result array joined by spaces using console.log(result.join(" ")).
DSA Typescript
Hint

Call the traversal starting from grandparent and print the names joined by spaces.