Description

Preorder traversal, is the traversal of a binary tree where we count the Node then the left node then the right.
?

Reach for when

You care about top-down processing - the node comes before its subtrees, so each node is handled before its children.

Runtime

O(n)

Visualization

Binary Tree-1784008572088.webp217

Pseudocode

PreOrder(node):
	if node is null:
		return
	save node.value
	PreOrder(node.left)
	PreOrder(node.right)

Code

def traverse(node, answer=[]):
	if not node:
		return answer

	answer.append(node.value)
	traverse(node.left, answer)
	traverse(node.right, answer)
	return answer