DEV Community

Justin Bermudez
Justin Bermudez

Posted on

1

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

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay