0
0
DSA Goprogramming~30 mins

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

Choose your learning style9 modes available
Tree Traversal Inorder Left Root Right
📖 Scenario: Imagine you have a family tree stored as a binary tree. You want to visit each family member in a special order: first the left child, then the parent, then the right child. This is called inorder traversal.
🎯 Goal: Build a simple binary tree and write code to traverse it inorder (left, root, right). Print the values of the nodes in this order.
📋 What You'll Learn
Create a binary tree with exactly 3 nodes: root with value 2, left child with value 1, right child with value 3
Create a function called inorderTraversal that takes the root node and returns a slice of integers representing the inorder traversal
Use recursion to visit left child, root, then right child
Print the slice returned by inorderTraversal
💡 Why This Matters
🌍 Real World
Tree traversals are used in many applications like searching, sorting, and organizing hierarchical data such as file systems or family trees.
💼 Career
Understanding tree traversal is essential for software engineers working with data structures, databases, and algorithms.
Progress0 / 4 steps
1
Create the binary tree nodes
Create a struct type called TreeNode with fields Val int, Left *TreeNode, and Right *TreeNode. Then create three variables: root with value 2, root.Left with value 1, and root.Right with value 3.
DSA Go
Hint

Define the struct first. Then create the root node with value 2. Assign left and right children with values 1 and 3.

2
Create a slice to hold traversal result
Inside main, create a variable called result of type []int to store the values during traversal.
DSA Go
Hint

Use result := []int{} to create an empty slice of integers.

3
Write the inorder traversal function
Write a function called inorderTraversal that takes a parameter node *TreeNode and returns a []int. Use recursion to visit the left child, then append the current node's value, then visit the right child. Combine the results and return the slice.
DSA Go
Hint

Check if node is nil, return empty slice. Recursively get left and right slices. Append left + current value + right.

4
Call traversal and print result
In main, call inorderTraversal(root) and assign the result to result. Then print result using fmt.Println. Import fmt package at the top.
DSA Go
Hint

Assign result = inorderTraversal(root) and print it with fmt.Println(result).