0
0
DSA Typescriptprogramming~30 mins

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

Choose your learning style9 modes available
Tree Traversal Postorder Left Right Root
📖 Scenario: You are working with a simple family tree where each person can have up to two children. You want to visit all family members in a special order: first the left child, then the right child, and finally the parent. This order is called postorder traversal.
🎯 Goal: Build a small tree using nodes, then write a function to visit all nodes in postorder (left, right, root) and collect their names in an array.
📋 What You'll Learn
Create a TreeNode class with name, left, and right properties
Create a tree with root node named "Grandparent", left child "Parent1", and right child "Parent2"
Add children to "Parent1": left child "Child1" and right child "Child2"
Write a function postorderTraversal that takes a TreeNode and returns an array of names in postorder
Print the array returned by postorderTraversal when called on the root node
💡 Why This Matters
🌍 Real World
Tree traversal is used in many real-world applications like file system navigation, organizing family trees, and parsing expressions.
💼 Career
Understanding tree traversal is important for software developers working with hierarchical data, databases, and algorithms.
Progress0 / 4 steps
1
Create the TreeNode class and build the tree
Create a class called TreeNode with a constructor that takes a name string and optional left and right TreeNode parameters. Then create the tree nodes exactly as follows: root node named "Grandparent", left child named "Parent1", right child named "Parent2", and add children to "Parent1" named "Child1" (left) and "Child2" (right). Connect the nodes properly.
DSA Typescript
Hint

Start by defining the TreeNode class with name, left, and right. Then create each node and connect them as children.

2
Create an array to collect traversal results
Create an empty array called result of type string[] that will store the names of nodes visited during traversal.
DSA Typescript
Hint

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

3
Write the postorderTraversal function
Write a function called postorderTraversal that takes a node of type TreeNode | null. If the node is not null, it should recursively call itself on the left child, then on the right child, and finally push the node.name into the result array.
DSA Typescript
Hint

Use recursion: call postorderTraversal on left, then right, then add current node's name to result.

4
Call the function and print the result
Call postorderTraversal with the grandparent node. Then print the result array using console.log(result).
DSA Typescript
Hint

Call postorderTraversal(grandparent) and then print result with console.log(result).