Bird
Raised Fist0
DSA Goprogramming

Tree Traversal Preorder Root Left Right in DSA Go

Choose your learning style10 modes available
Mental Model
Visit the root node first, then explore the left subtree, and finally the right subtree.
Analogy: Imagine reading a book: first you look at the title (root), then read the left page (left subtree), and then the right page (right subtree).
    1
   / \
  2   3
 / \
4   5
Dry Run Walkthrough
Input: Tree with nodes: 1 as root, 2 as left child, 3 as right child, 4 as left child of 2, 5 as right child of 2
Goal: Print nodes in preorder: root first, then left subtree, then right subtree
Step 1: Visit root node 1
Visited: 1
Why: Start traversal at the root
Step 2: Traverse left subtree starting at node 2
Visited: 1 -> 2
Why: After root, visit left subtree
Step 3: Traverse left subtree of node 2, visit node 4
Visited: 1 -> 2 -> 4
Why: Preorder visits root of subtree before children
Step 4: Back to node 2, traverse right subtree, visit node 5
Visited: 1 -> 2 -> 4 -> 5
Why: After left child, visit right child
Step 5: Back to root 1, traverse right subtree, visit node 3
Visited: 1 -> 2 -> 4 -> 5 -> 3
Why: After left subtree, visit right subtree
Result:
1 -> 2 -> 4 -> 5 -> 3 -> null
Annotated Code
DSA Go
package main

import "fmt"

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

func preorder(root *TreeNode) {
    if root == nil {
        return
    }
    fmt.Printf("%d -> ", root.Val) // visit root first
    preorder(root.Left)           // traverse left subtree
    preorder(root.Right)          // traverse right subtree
}

func main() {
    // Construct the tree:
    //     1
    //    / \
    //   2   3
    //  / \
    // 4   5
    root := &TreeNode{Val: 1}
    root.Left = &TreeNode{Val: 2}
    root.Right = &TreeNode{Val: 3}
    root.Left.Left = &TreeNode{Val: 4}
    root.Left.Right = &TreeNode{Val: 5}

    preorder(root)
    fmt.Print("null\n")
}
if root == nil { return }
stop traversal when reaching a leaf's child (nil)
fmt.Printf("%d -> ", root.Val) // visit root first
visit current node before children
preorder(root.Left) // traverse left subtree
recursively traverse left subtree
preorder(root.Right) // traverse right subtree
recursively traverse right subtree
OutputSuccess
1 -> 2 -> 4 -> 5 -> 3 -> null
Complexity Analysis
Time: O(n) because each node is visited exactly once
Space: O(h) where h is the height of the tree due to recursion stack
vs Alternative: Compared to iterative traversal, recursive preorder is simpler but uses call stack; iterative uses explicit stack but can be more complex
Edge Cases
empty tree (root is nil)
function returns immediately without printing anything
DSA Go
if root == nil {
        return
    }
tree with single node
prints the single node value followed by null
DSA Go
if root == nil {
        return
    }
When to Use This Pattern
When you need to process the root node before its children in a tree, use preorder traversal to visit nodes in root-left-right order.
Common Mistakes
Mistake: Visiting left or right child before the root node
Fix: Print or process the root node value before recursive calls to left and right children
Summary
Visits the root node first, then recursively visits left and right subtrees.
Use when you want to process the root before its children, such as copying a tree or prefix expression evaluation.
The key insight is to handle the root node before diving into subtrees.

Practice

(1/5)
1. What is the order of nodes visited in a preorder tree traversal?
easy
A. Root, Left, Right
B. Left, Root, Right
C. Left, Right, Root
D. Right, Left, Root

Solution

  1. Step 1: Understand preorder traversal definition

    Preorder traversal visits the root node first, then the left subtree, and finally the right subtree.
  2. Step 2: Match the order with options

    Root, Left, Right matches the order Root, Left, Right exactly.
  3. Final Answer:

    Root, Left, Right -> Option A
  4. Quick Check:

    Preorder = Root, Left, Right [OK]
Hint: Remember preorder starts with root node first [OK]
Common Mistakes:
  • Confusing preorder with inorder or postorder
  • Swapping left and right subtree order
  • Starting traversal from left child instead of root
2. Which of the following Go function signatures correctly represents a preorder traversal function for a binary tree node Node?
easy
A. func preorder(root *Node) { if root == nil { return } preorder(root.Left) preorder(root.Right) fmt.Println(root.Value) }
B. func preorder(root *Node) { if root == nil { return } fmt.Println(root.Value) preorder(root.Left) preorder(root.Right) }
C. func preorder(root *Node) { if root == nil { return } preorder(root.Right) fmt.Println(root.Value) preorder(root.Left) }
D. func preorder(root *Node) { if root == nil { return } preorder(root.Left) fmt.Println(root.Value) preorder(root.Right) }

Solution

  1. Step 1: Recall preorder traversal order

    Preorder visits root first, then left subtree, then right subtree.
  2. Step 2: Check function order

    func preorder(root *Node) { if root == nil { return } fmt.Println(root.Value) preorder(root.Left) preorder(root.Right) } prints root value first, then recursively visits left and right children, matching preorder.
  3. Final Answer:

    func preorder(root *Node) { if root == nil { return } fmt.Println(root.Value) preorder(root.Left) preorder(root.Right) } -> Option B
  4. Quick Check:

    Print root before children calls [OK]
Hint: Print root value before recursive calls [OK]
Common Mistakes:
  • Printing after recursive calls (postorder)
  • Swapping left and right recursive calls
  • Missing nil check for root
3. Given the binary tree below, what is the preorder traversal output?

    10
   /  \
  5    15
 /    /  \
3    12  20
func preorder(root *Node) { if root == nil { return } fmt.Print(root.Value, " ") preorder(root.Left) preorder(root.Right) }
medium
A. [5, 3, 10, 15, 12, 20]
B. [3, 5, 10, 12, 15, 20]
C. [10, 15, 20, 12, 5, 3]
D. [10, 5, 3, 15, 12, 20]

Solution

  1. Step 1: Start at root node 10

    Print 10, then traverse left subtree.
  2. Step 2: Traverse left subtree (5, then 3)

    Print 5, then left child 3, which has no children.
  3. Step 3: Traverse right subtree (15, 12, 20)

    Print 15, then left child 12, then right child 20.
  4. Final Answer:

    [10, 5, 3, 15, 12, 20] -> Option D
  5. Quick Check:

    Preorder = Root, Left, Right [OK]
Hint: Follow root, then left subtree, then right subtree order [OK]
Common Mistakes:
  • Mixing preorder with inorder or postorder output
  • Visiting right subtree before left
  • Skipping leaf nodes
4. The following Go code attempts a preorder traversal but produces incorrect output. What is the error?

func preorder(root *Node) {
  if root == nil {
    return
  }
  preorder(root.Left)
  fmt.Print(root.Value, " ")
  preorder(root.Right)
}
medium
A. The function uses fmt.Print instead of fmt.Println
B. The function does not check for nil root
C. The root value is printed after left subtree traversal, not before
D. The right subtree is traversed before the left subtree

Solution

  1. Step 1: Analyze print position in code

    The root value is printed after preorder(root.Left), so root is visited after left subtree.
  2. Step 2: Compare with preorder definition

    Preorder requires visiting root first, then left, then right. This code visits left first, then root, then right (inorder).
  3. Final Answer:

    The root value is printed after left subtree traversal, not before -> Option C
  4. Quick Check:

    Print root before children for preorder [OK]
Hint: Print root value before recursive calls to fix order [OK]
Common Mistakes:
  • Confusing preorder with inorder traversal
  • Ignoring nil check (though present here)
  • Thinking print function choice affects traversal order
5. You want to collect all node values of a binary tree in preorder traversal into a slice in Go. Which code snippet correctly does this?
hard
A. func preorder(root *Node, result *[]int) { if root == nil { return } *result = append(*result, root.Value) preorder(root.Left, result) preorder(root.Right, result) }
B. func preorder(root *Node, result []int) []int { if root == nil { return result } result = append(result, root.Value) preorder(root.Left, result) preorder(root.Right, result) return result }
C. func preorder(root *Node) []int { if root == nil { return nil } left := preorder(root.Left) right := preorder(root.Right) return append(left, append(right, root.Value)...) }
D. func preorder(root *Node, result *[]int) { if root == nil { return } preorder(root.Left, result) preorder(root.Right, result) *result = append(*result, root.Value) }

Solution

  1. Step 1: Understand preorder collection logic

    Preorder means add root value first, then traverse left and right subtrees.
  2. Step 2: Check each option's order and parameter usage

    func preorder(root *Node, result *[]int) { if root == nil { return } *result = append(*result, root.Value) preorder(root.Left, result) preorder(root.Right, result) } appends root value first, then recursively traverses left and right, using pointer to slice to collect values correctly.
  3. Final Answer:

    func preorder(root *Node, result *[]int) { if root == nil { return } *result = append(*result, root.Value) preorder(root.Left, result) preorder(root.Right, result) } -> Option A
  4. Quick Check:

    Append root first, use pointer to slice [OK]
Hint: Append root value before recursive calls, pass slice pointer [OK]
Common Mistakes:
  • Appending after recursive calls (wrong order)
  • Passing slice by value and expecting changes
  • Appending right subtree before left subtree
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard