How does level-order traversal work using BFS?
LeetCode Patterns Flashcards: Trees, DFS, BFS, Traversals, BST Properties
Аудио-карточка · 0:32Nortren·
How does level-order traversal work using BFS?
0:32
Initialize a queue with the root node. While the queue is not empty, record the queue size as the number of nodes at the current level. Process exactly that many nodes by dequeuing each one, recording its value, and enqueuing its left and right children if they exist. After processing all nodes at one level, the queue contains exactly the nodes of the next level. This naturally groups nodes by level and runs in O of n time and O of w space. Level-order traversal is the foundation for problems like finding the maximum value at each level, the right-side view of a tree, and the zigzag traversal.
neetcode.io