題目
原題頁面:https://leetcode.com/problems/binary-tree-level-order-traversal/
題目型別:Tree, Breadth-first Search
難度評價:Easy
類似題目:(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}".
分析
二叉樹的層次遍歷應用在LeetCode中出現了好幾次。一般而言二叉樹層次遍歷是用佇列,但是由於本題要區分出每一層,因此用兩個陣列分別模擬佇列。
程式碼
1 | class Solution: |
本文地址:https://xnerv.wang/zh-tw/leetcode-binary-tree-level-order-traversal/
