Recursion

Preorder Traversal

Tree DFS

This is a really basic problem to make sure you know how to implement a preorder traversal - you won't get something this easy in an interview.

Problem: Given the root node of a binary tree, return the preorder traversal of its nodes.

Example:

Preorder Traversal - image
=> returns [1,2,3,4,5,6,7]\notag \large \texttt{=> returns [1,2,3,4,5,6,7]}

Hint: Remember, the preorder traversal first does something on a node "pre" doing it on its children.

First Few Test Cases:
preorderArray(TreeNode.of([1, 2, 5, 3, 4, 6, 7]))
# [1, 2, 3, 4, 5, 6, 7]
preorderArray(TreeNode.of([1, 2, 3]))
# [1, 2, 3]
preorderArray(TreeNode.of([1]))
# [1]

We want to do a preorder traversal over all the nodes in the tree.

preorder(root)

1. Recursion

The recursion for a preorder traversal is to visit the current node, then all the nodes to the left, then right, c L R.

Preorder Traversal - image

When we visit each node, we add its value to an array. Here's the recursion:

values = []
def preorder(node):
    values.append(node.val) # add value to array
    preorder(node.left)     # visit left children
    preorder(node.right)    # visit right children

2. Base case

This recursion will keep calling itself on deeper and deeper nodes in the tree. Eventually, it calls itself on a null node, preorder(null). In this case, we don't want to traverse any further and we should just do nothing.

preorder(null) = 'do nothing'

3. Code

To code the preorder traversal function, we just combine the recursion and base case. After calling this function, we return the values array that it filled in.

def preorderArray(root):

    values = []
    
    def preorder(node):
        # base case
        if node is None:
            return
        
        # recursion
        values.append(node.val)
        preorder(node.left)
        preorder(node.right)

    preorder(root) # fills in `values` array

    return values

Time Complexity O(n)O(n). We walk through all of the nodes in the tree, which is nn nodes total.

Space Complexity O(n)O(n). The recursive function calls are stored inside of the Call Stack, which grows up to the depth of the tree. The tree might be a flat line, in which case it's nn nodes deep.

Mark as Completed:
Submits:
preorderArray
Imports:
TreeNode
Test your code to get an output here!
preorderArray(
)
Test your code to get an output here!