mirror of
https://github.com/krahets/hello-algo.git
synced 2026-06-18 01:37:17 +08:00
* Add Russian docs site baseline * Add Russian localized codebase * Polish Russian code wording * Update ru code translation. * Update code translation and chapter covers. * Fix pythontutor extraction. * Add README and landing page. * placeholder of profiles * Use figures of English version * Remove chapter paperbook
36 lines
1.0 KiB
Go
36 lines
1.0 KiB
Go
// File: binary_tree_bfs.go
|
|
// Created Time: 2022-11-26
|
|
// Author: Reanon (793584285@qq.com)
|
|
|
|
package chapter_tree
|
|
|
|
import (
|
|
"container/list"
|
|
|
|
. "github.com/krahets/hello-algo/pkg"
|
|
)
|
|
|
|
/* Обход в ширину */
|
|
func levelOrder(root *TreeNode) []any {
|
|
// Инициализировать очередь и добавить корневой узел
|
|
queue := list.New()
|
|
queue.PushBack(root)
|
|
// Инициализировать срез для хранения последовательности обхода
|
|
nums := make([]any, 0)
|
|
for queue.Len() > 0 {
|
|
// Извлечение из очереди
|
|
node := queue.Remove(queue.Front()).(*TreeNode)
|
|
// Сохранить значение узла
|
|
nums = append(nums, node.Val)
|
|
if node.Left != nil {
|
|
// Поместить левый дочерний узел в очередь
|
|
queue.PushBack(node.Left)
|
|
}
|
|
if node.Right != nil {
|
|
// Поместить правый дочерний узел в очередь
|
|
queue.PushBack(node.Right)
|
|
}
|
|
}
|
|
return nums
|
|
}
|