← All solutions

Binary Tree Preorder Traversal

May 30, 2025 • Go •stack, tree, depth first search, binary tree • easy

Problem

  • Given the root of a binary tree, return the preorder traversal of its nodes' values.

Reflections

Memorized at this point.

Go Solution

func preorderTraversal(root *TreeNode) []int {
    var res []int
    var dfs func(root *TreeNode) 
    dfs = func(root *TreeNode) {
        if root == nil {
            return 
        }

        res = append(res, root.Val)
        dfs(root.Left)
        dfs(root.Right)
    }

    dfs(root)

    return res
}

Performance

  • Runtime beats: 100%
  • Memory beats: 32%

Complexity

  • Time: O(n)
  • Space: O(n)
LeetCode Problem Link