Today we will do a problem in LeetCode, the original link: finger Offer 32 – print binary tree I from top to bottom
Topic describes
- Each node of the binary tree is printed from top to bottom, and nodes of the same level are printed from left to right.
- Such as:
- Given a binary tree: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
Copy the code
- Returns:
,9,20,15,7 [3]Copy the code
- Tip:
The total number of nodes <= 1000Copy the code
Thought analysis
- Binary tree traversal using dual-ended queues: collections.deque()
code
# Python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root: return []
res, queue = [], collections.deque()
queue.append(root)
while queue:
node = queue.popleft()
res.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
return res
Copy the code
conclusion
- collections.deque()
- Append () : append function
- Popleft () : fetch data from the header
The appendix
- Leetcode-cn.com/problems/co…
This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign