0
0
DSA Typescriptprogramming~30 mins

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

Choose your learning style9 modes available
Tree Traversal Inorder Left Root Right
📖 Scenario: You have a simple family tree where each person can have a left child and a right child. You want to visit each person in a special order: first the left child, then the person, then the right child. This is called inorder traversal.
🎯 Goal: Build a small tree using nodes, then write code to visit and print the nodes in inorder (left, root, right) order.
📋 What You'll Learn
Create a TreeNode class with value, left, and right properties
Create a tree with exactly 3 nodes: root with value 1, left child with value 2, right child with value 3
Write a function called inorderTraversal that visits nodes in left-root-right order
Print the values of nodes in inorder traversal separated by spaces
💡 Why This Matters
🌍 Real World
Tree traversal is used in many real-world tasks like searching family trees, organizing files, or evaluating expressions.
💼 Career
Understanding tree traversal is important for software developers working with data structures, 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 value (number) and sets left and right to null. Then create three nodes: root with value 1, root.left with value 2, and root.right with value 3.
DSA Typescript
Hint

Define the class with value, left, and right. Then create the root and assign left and right children.

2
Create an array to store traversal results
Create an empty array called result to store the values of nodes visited during inorder traversal.
DSA Typescript
Hint

Use const result: number[] = []; to create an empty array for storing values.

3
Write the inorder traversal function
Write a function called inorderTraversal that takes a node of type TreeNode | null. If the node is not null, first call inorderTraversal on node.left, then push node.value to result, then call inorderTraversal on node.right.
DSA Typescript
Hint

Use recursion: visit left child, then current node, then right child.

4
Run inorder traversal and print the result
Call inorderTraversal with root as argument. Then print the result array values joined by spaces using console.log(result.join(' ')).
DSA Typescript
Hint

Call the function with root and print the result array joined by spaces.