Description,
You need to find the largest value in each row of a binary tree. The leetcode link
Example,
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
BFS implemted in Java
Natually, the level order BFS is the most straight forward way to tackle this problem – traverse the tree level by level, and find the node with largest value.
Time complexity: O(n)
RUntime: 10ms
Note:
The Queue and Deque both work in BFS. The implementations of Queue/Deque have pros & cons, but in this specific problem, they perform almost the same.
Runtime: 10ms
Pre-order DFS in Python
This problem could also be solved by pre-order DFS.
Create an empty bucket, whenever traversing to a new level, increase bucket size by 1.
When reaching a level already exists in the bucket, compare the existing value with the current node’s vaue. Update the bucket value to the larger one.
Because this is an one-pass traversal, the time complexity is O(n), where n is the tree node count.