Depth First Search (DFS)¶

Depth First Search is a search algorithm that explores the tree by going as deep as possible along each branch first¶

Animation from Wikipedia¶

This DFS first explores left branches (note that the tree in the animation is not a binary tree)¶

Implementation¶

helper is called recursively, it is first called on the left child and it will explore left branch until reaching the end. Once the end is reach on the left branch, the right branch is explored.¶

Binary Tree¶

In [ ]:
def get_depth_dfs(root):
    return(helper(root))

def helper(node):
    if not node:
        return(0)
    else:
        return(1 + max(helper(node.left), helper(node.right)))

Tree¶

In [ ]:
def get_depth_dfs(root):
    return(helper(root))

def helper(node):
    if not node:
        return(0)
    else:
        return(1 + max([helper(child_node) for child_node in node.children]))