0
0
DSA Javascriptprogramming~30 mins

Tree Traversal Preorder Root Left Right in DSA Javascript - 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 has a name and may have children. You want to visit each person starting from the root (the oldest ancestor), then visit their children from left to right.
🎯 Goal: Build a program that creates a tree structure and prints the names of all family members using preorder traversal (root, then left child, then right child).
📋 What You'll Learn
Create a tree node structure with name, left, and right properties
Create a tree with exactly three nodes: root, left child, and right child
Write a recursive function called preorderTraversal that visits nodes in preorder
Print the names of the nodes in preorder traversal order separated by spaces
💡 Why This Matters
🌍 Real World
Tree traversal is used in many real-world applications like organizing family trees, file systems, and decision trees.
💼 Career
Understanding tree traversal is important for software developers working with hierarchical data, databases, and algorithms.
Progress0 / 4 steps
1
Create the tree nodes
Create three variables called root, leftChild, and rightChild. Each should be an object with a name property set to exactly "Grandparent", "Parent", and "Uncle" respectively. Also, set their left and right properties to null.
DSA Javascript
Hint

Each node is an object with name, left, and right. Start by creating these three objects with the exact names and values.

2
Link the nodes to form the tree
Set the left property of root to leftChild and the right property of root to rightChild.
DSA Javascript
Hint

Assign the leftChild and rightChild objects to the left and right properties of root.

3
Write the preorder traversal function
Write a recursive function called preorderTraversal that takes a node as input. It should visit the node by adding its name to an array called result, then recursively visit the left child, then the right child. Declare result as an empty array before calling the function.
DSA Javascript
Hint

Use a function that first adds the current node's name to result, then calls itself on the left child, then on the right child. Stop when the node is null.

4
Print the preorder traversal result
Print the contents of the result array as a single string with names separated by spaces using console.log.
DSA Javascript
Hint

Use console.log(result.join(" ")) to print the names separated by spaces.