Today we are going to do a problem in LeetCode, link to the original problem: finger Offer 32 – Print binary tree II from top to bottom
Topic describes
- The binary tree is printed from top to bottom layer, with nodes of the same layer printed from left to right, each layer printed to a row.
- Such as:
- Given a binary tree: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
Copy the code
- Returns the result of its hierarchical traversal:
[[3], [9,20], [15,7]Copy the code
- Tip:
The total number of nodes <= 1000Copy the code
Thought analysis
- Binary tree traversal using dual-ended queues: collections.deque()
- Results are saved using an ordered dictionary: collections.ordereddict ()
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[List[int]]
"""
if not root: return []
res_dict, queue = collections.OrderedDict(), collections.deque()
level = 0
queue.append((root, level))
while queue:
node, level = queue.popleft()
if level in res_dict:
res_dict[level].append(node.val)
else:
res_dict[level] = [node.val]
level += 1
if node.left: queue.append((node.left, level))
if node.right: queue.append((node.right, level))
return res_dict.values()
Copy the code
conclusion
- collections.deque()
- Append () : append function
- Popleft () : fetch data from the header
- collections.OrderedDict()
- Values () : Returns an array of values
This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign