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).
The number of nodes in the tree is in the range [0, 2000].
-1000 <= Node.val <= 1000
Solutions
Solution 1: BFS
We can use the BFS (Breadth-First Search) method to solve this problem. First, enqueue the root node, then continuously perform the following operations until the queue is empty:
Traverse all nodes in the current queue, store their values in a temporary array $t$, and then enqueue their child nodes.
Store the temporary array $t$ in the answer array.
Finally, return the reversed answer array.
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.
1 2 3 4 5 6 7 8 91011121314151617181920212223
# 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 = rightclassSolution:deflevelOrderBottom(self,root:Optional[TreeNode])->List[List[int]]:ans=[]ifrootisNone:returnansq=deque([root])whileq:t=[]for_inrange(len(q)):node=q.popleft()t.append(node.val)ifnode.left:q.append(node.left)ifnode.right:q.append(node.right)ans.append(t)returnans[::-1]