Files
2018-10-16 21:32:40 +05:30

51 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: Breadth-First Search
localeTitle: Поиск по ширине
---
## Поиск по ширине
Давайте сначала определим класс `Tree` который будет использоваться для реализации алгоритма первого поиска Breadth.
```python
class Tree:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
```
Алгоритм поиска ширины ширины перемещается с одного уровня на другой, начиная с корня дерева. Мы будем использовать для этого `queue` .
```python
def bfs(root_node):
queue = [root_node]
while queue:
top_element = queue.pop()
print("Node processed: ",top_element)
if top_element.left:
queue.append(top_element.left)
if top_element.right:
queue.append(top_element.right)
```
Мы можем легко изменить приведенный выше код, чтобы напечатать уровень каждого узла.
```python
def bfs(root_node):
queue = [(root_node, 0)]
while queue:
top_element, level = queue.pop()
print("Node processed: {} at level {}".format(top_element, level))
if top_element.left:
queue.append((top_element.left, level + 1))
if top_element.right:
queue.append((top_element.right, level + 1))
```
| Сложность | Время | Космос | | ----- | ------ | ------ | | BFS | n | n |