Preorder traversal

The node first, then its left subtree, then its right subtree. Parents always come before their children.

Time O(n)Space O(h)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Record the node the moment you arrive, then handle the children. The result starts with the root and lists every parent before anything beneath it.

Code

public static void Preorder(TreeNode node, List<int> result) {
    if (node == null) return;
    result.Add(node.val);
    Preorder(node.left, result);
    Preorder(node.right, result);
}
static void preorder(TreeNode node, List<Integer> result) {
    if (node == null) return;
    result.add(node.val);
    preorder(node.left, result);
    preorder(node.right, result);
}
void preorder(TreeNode* node, vector<int>& result) {
    if (!node) return;
    result.push_back(node->val);
    preorder(node->left, result);
    preorder(node->right, result);
}
def preorder(node: TreeNode | None, result: list[int]) -> None:
    if node is None: return
    result.append(node.val)
    preorder(node.left, result)
    preorder(node.right, result)

Tips

In the .NET library

A recursive file listing that prints each directory before its contents, like Directory.EnumerateDirectories with your own recursion, is a preorder walk.