Pre-order Traversal

Tree Traversal Algorithm: How do you traverse a binary tree in pre-order (recursively and iteratively)? What are its use cases?

Assume:

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.right = None
        self.left = None

Iterative

def preorder_iterative(node):
    res = []
    if not node:
        return res
    stack = []
    stack.append(node)
    while stack:
        node = stack.pop()
        res.append(node.val) # additional logic here!
		if node.right:
            stack.append(node.right)
        if node.left:
            stack.append(node.left)
    return res

Recursive

def preorder_recursive(node, res=None):
    if node is None:
        return []
    if res is None:
        res = []
    res.append(node.val) # additional logic here!
    preorder_recursive(node.left, res)
    preorder_recursive(node.right, res)
    return res