Trees

Time:

  • Usually O(n) (visit each node)

  • O(n*k) where k is work at each node

Space:

  • O(n) - Straight line, all on stack

  • O(longn) - balanced tree

Depth: O(logn)

DFS

Pre-order: Operate on node on way down. (Logic before - pre)

def preorder_dfs(node):
    if not node:
        return

    print(node.val)
    preorder_dfs(node.left)
    preorder_dfs(node.right)
    return

In an increasing tree (root < child) this gives us increasing order.

In-order: Order on the way up. (logic in middle - in)

In BST translates to in order.

Do left, then print val, then right.

Post-order: Go to leaves before anything else. (logic after - post)

BFS

O(V+E)

(balanced tree) The final level in a perfect binary tree has n/2 nodes, so BFS uses O(n) space

To traverse levels, use:

Trie

A trie (pronounced “try”) is a tree-based data structure that stores strings efficiently by sharing common prefixes. Also called a prefix tree, a trie enables fast string search, insertion, and deletion operations in O(L) time, where L is the string length.

Last updated