题目
原题页面: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/leetcode-binary-tree-level-order-traversal/
