Depth-First Search (DFS) with Python

jabermudez11

Justin Bermudez

Posted on October 11, 2020

Depth-First Search (DFS) with Python

Given a Node class that has a name and array of optional children nodes. When put together, these nodes form a tree-like structure.


class Node:
    def __init__(self, name):
        self.children = []
        self.name = name
    def addChild(self, name):
        self.children.append(Node(name))
        return self
    def depthFirstSearch(self, array):
        array.append(self.name)
        for child in self.children:
            child.depthFirstSearch(array)
        return array
💖 💪 🙅 🚩
jabermudez11
Justin Bermudez

Posted on October 11, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related