515 Find Largest Value in Each Tree Row

1. Question

You need to find the largest value in each row of a binary tree.

Example:

Input:
          1
         / \
        3   2
       / \   \  
      5   3   9 


Output:
 [1, 3, 9]

2. Implementation

(1) BFS

(2) DFS

3. Time & Space Complexity

BFS: 时间复杂度是O(n), 空间复杂度是O(Math.max(h, w)), h是树的高度,w是树的一层中包含最多node的个数

DFS:时间复杂度是O(n), 空间复杂度是O(h)

Last updated

Was this helpful?