Binary Tree Level Order Traversal
Clarify the problem:
- The problem requires us to perform a level order traversal of a binary tree and return the nodes at each level as a list of lists.
- Level order traversal visits the nodes at each level from left to right, starting from the root level.
- We need to implement a function that takes the root of the binary tree as input and returns the level order traversal as a list of lists.
Analyze the problem:
- Input: The root of a binary tree.
- Output: A list of lists containing the nodes at each level of the binary tree.
- Constraints:
- The number of nodes in the binary tree is in the range [0, 1000].
- The values of the nodes are unique.
Design an algorithm:
- We can use a breadth-first search (BFS) approach to perform the level order traversal.
- Create an empty list to store the result.
- Create an empty queue to store the nodes to be processed.
- Enqueue the root node into the queue.
- While the queue is not empty:
- Create an empty list to store the nodes at the current level.
- Get the current size of the queue (which represents the number of nodes at the current level).
- Iterate through the nodes at the current level:
- Dequeue a node from the queue.
- Add the node's value to the list of nodes at the current level.
- Enqueue the node's left and right children (if they exist) into the queue.
- Append the list of nodes at the current level to the result list.
- Return the result list.
Explain your approach:
- We will implement a function called
levelOrder
to solve the problem. - The function will take the root of the binary tree as input.
- We will create an empty list called
result
to store the level order traversal. - We will create an empty queue called
queue
to store the nodes to be processed. - We will enqueue the root node into the queue.
- While the queue is not empty, we will:
- Create an empty list called
level_nodes
to store the nodes at the current level. - Get the current size of the queue.
- Iterate
i
from 0 to the current queue size:- Dequeue a node from the queue.
- Add the value of the dequeued node to
level_nodes
. - Enqueue the left and right children of the dequeued node (if they exist) into the queue.
- Append
level_nodes
toresult
.
- Create an empty list called
- Finally, we return
result
.
- We will implement a function called
Write clean and readable code:
pythonclass TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def levelOrder(root): if not root: return [] result = [] queue = [] queue.append(root) while queue: level_nodes = [] level_size = len(queue) for _ in range(level_size): node = queue.pop(0) level_nodes.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) result.append(level_nodes) return result
Test your code:
- To test the code, we need to create a binary tree and verify that the level order traversal is correct.
- Let's create a binary tree with the following structure:
1
/
2 3 / \
4 5 6 - The level order traversal should be: [[1], [2, 3], [4, 5, 6]]
- We can use the following code to test the
levelOrder
function:
python# Create the binary tree root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) root.right.right = TreeNode(6) # Perform level order traversal result = levelOrder(root) # Check if the level order traversal is correct assert result == [[1], [2, 3], [4, 5, 6]]
We have tested the code with a sample binary tree and verified that the level order traversal is correct.
Optimize if necessary:
- The current solution has a time complexity of O(N), where N is the number of nodes in the binary tree.
- This is because we visit each node once during the level order traversal.
- The space complexity is also O(N) because in the worst case, the queue can hold all the nodes at the maximum level.
Handle error cases:
- The code handles the case when the root is None and returns an empty list in that case.
- The code assumes that the input is a valid binary tree.
Discuss complexity analysis:
- Let N be the number of nodes in the binary tree.
- The time complexity of the solution is O(N) because we visit each node once during the level order traversal.
- The space complexity is also O(N) because in the worst case, the queue can hold all the nodes at the maximum level.