Skip to content

Instantly share code, notes, and snippets.

@bavadim
Created April 3, 2024 07:36
Show Gist options
  • Save bavadim/a2cb0c30805984fcaa36db8be716b622 to your computer and use it in GitHub Desktop.
Save bavadim/a2cb0c30805984fcaa36db8be716b622 to your computer and use it in GitHub Desktop.
Code snippet
def dfs(tree):
"""Функция для обхода дерева в глубину, представленного в виде вложенных списков."""
if not isinstance(tree, list): # Если текущий узел не является списком, возвращаем его
return [tree]
result = []
for element in tree:
result.extend(dfs(element)) # Рекурсивно обходим каждый элемент
return result
# Пример использования
tree = ['a', ['b', ['d'], ['e']], ['c', ['f'], ['g']]]
print(dfs(tree))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment