Promble
link: https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/
Given the root of a binary tree, return the bottom-up level order traversal of its nodes’ values. (i.e., from left to right, level by level from leaf to root).
Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]
Input: root = [1]
Output: [[1]]
Input: root = []
Output: []
Approach 1
BFS
Thought
- judge if root is None
- def queue:deque, from collections.deque
- append root to queue
- def output:list to store the result
- while queue
- def noeds_in_curr_level:list to store the current level nodes
- def length is len(queue) # the length will update, 1.
- loop in range(length)
- popleft from queue, to curr_node
- append curr_node.val to nodes_in_curr_level
- if curr_node.left: queue.append(curr_node.left)
- if curr_node.right: queue.append(curr_node.right)
- output.append(nodes_in_curr_level)
- return reversed(output)
📓the leetcode def the TreeNode, so we should notice the structure of this class.
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
class Solution:
def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
queue = deque()
queue.append(root)
output = []
while queue:
nodes_in_curr_level = []
length = len(queue)
for _ in range(length):
curr_node = queue.popleft()
nodes_in_curr_level.append(curr_node.val)
# print(nodes_in_curr_level)
# print(queue)
if curr_node.left:
queue.append(curr_node.left)
if curr_node.right:
queue.append(curr_node.right)
# print(queue)
output.append(nodes_in_curr_level)
return reversed(output)