0
0
DSA Typescriptprogramming~30 mins

Left Side View of Binary Tree in DSA Typescript - Build from Scratch

Choose your learning style9 modes available
Left Side View of Binary Tree
📖 Scenario: You are working with a binary tree data structure, which is like a family tree but each parent has at most two children: left and right. You want to see the tree from the left side, so you only see the first node at each level when looking from the left.
🎯 Goal: Build a program that finds the left side view of a binary tree. This means you will print the nodes visible when the tree is seen from the left side, one node per level.
📋 What You'll Learn
Create a binary tree using a TreeNode class with val, left, and right properties.
Create a variable root representing the root node of the binary tree with exact values.
Create a variable result to store the left side view nodes.
Write a function leftSideView that takes the root node and returns an array of node values visible from the left side.
Print the result array.
💡 Why This Matters
🌍 Real World
Binary trees are used in many computer applications like organizing data, searching quickly, and representing hierarchical information such as file systems or organizational charts.
💼 Career
Understanding tree traversal and views is important for software developers working with data structures, algorithms, and system design.
Progress0 / 4 steps
1
Create the Binary Tree Structure
Create a class called TreeNode with a constructor that takes a number val and optional left and right nodes. Then create a variable called root representing this exact binary tree:

1
/ \
2 3
/ \
4 5

Use new TreeNode to create nodes with values 1, 2, 3, 4, and 5 arranged as shown.
DSA Typescript
Hint

Remember to create the TreeNode class first, then build the tree from bottom to top using new TreeNode.

2
Create the Result Array
Create a variable called result and set it to an empty array of numbers. This will hold the values of the nodes visible from the left side.
DSA Typescript
Hint

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

3
Write the Left Side View Function
Write a function called leftSideView that takes a parameter root of type TreeNode | null and returns an array of numbers. Use a helper function inside it to do a depth-first search (DFS) that visits nodes level by level, always going left first. Add the first node you visit at each level to the result array.
DSA Typescript
Hint

Use a helper function dfs inside leftSideView to visit nodes. Add the node value to result only if this is the first node at this level.

4
Print the Left Side View Result
Call the function leftSideView with the root node and store the result in the result variable. Then print the result array using console.log.
DSA Typescript
Hint

Call leftSideView(root) and print the returned array with console.log.