Problem
Problem page: https://leetcode.com/problems/binary-tree-level-order-traversal/
Topics: Tree, Breadth-first Search
Difficulty: Easy
Similar problems: (M) Binary Tree Zigzag Level Order Traversal, (E) Binary Tree Level Order Traversal II, (E) Minimum Depth of Binary Tree
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree{3,9,20,#,#,15,7},
1
2
3
4
5 3
/ \
9 20
/ \
15 7return its level order traversal as:
1
2
3
4
5 [
[3],
[9,20],
[15,7]
]confused what
"{1,#,2,3}"means?OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
2
3
4
5
6
7 1
/ \
2 3
/
4
\
5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}".
Analysis
Level-order traversal of a binary tree has come up several times on LeetCode. It usually uses a queue, but this problem needs to keep the levels separate, so I use two arrays, each acting as a queue.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-binary-tree-level-order-traversal/
