LeetCode #102: Binary Tree Level Order Traversal
https://leetcode.com/problems/binary-tree-level-order-traversal/description/
To solve the problem, we will use a breadth-first search (BFS) approach. We will use a queue to keep track of the nodes in the tree that we have yet to visit. Starting with the root node, we will add it to the queue. Then, while the queue is not empty, we will remove the first node from the queue, add its value to the current level list, and add its left and right children to the queue if they exist. Once we have finished processing all the nodes in the current level, we add the current level list to the final result list.
Steps:
- Define a function
levelOrder
that takes theroot
node of the binary tree as input and returns a list of lists containing the values of nodes at each level of the tree. - Create an empty list called
ret_list
to store the final result. - Create a queue called
que
and add theroot
node to it. - While the queue is not empty, do the following: a. Create an empty list called
level
to store the values of nodes at the current level. b. Iterate over all the nodes in the current level of the tree by using a loop that runslen(que)
times. c. Remove the first node from the queue and store it in a variable calledcurr
. d. If the current nodecurr
is notNone
, add its value to thelevel
list and add its left and right children to theque
queue. e. If thelevel
list is not empty, append it to theret_list
list. - Return the
ret_list
list.
Here is the completed solution in Python3:
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
que = [root]
ret_list = []
while que:
level = []
for i in range(len(que)):
curr = que.pop(0)
if curr:
level.append(curr.val)
que.append(curr.left)
que.append(curr.right)
if level:
ret_list.append(level)
return ret_list
Time Complexity: The time complexity of this algorithm is O(n), where n is the number of nodes in the binary tree. This is because we need to visit each node exactly once.
Space Complexity: The space complexity of this algorithm is O(n), where n is the maximum number of nodes at any level of the binary tree. This is because we need to store all the nodes at each level in the queue before processing them.