Sponsored
Sponsored
The BFS approach involves traversing the tree level by level and keeping track of the largest value at each level. We employ a queue data structure to facilitate level-wise traversal and maintain a list to store the maximum values for each row.
Time Complexity: O(n) where n is the number of nodes in the tree, since each node is processed exactly once. Space Complexity: O(n) due to the storage required to keep the queue and the result array.
1var largestValues = function(root) {
2 if (!root) return [];
3 const result = [];
4 const queue = [root];
5
6 while (queue.length) {
7 let levelMax = -Infinity;
8 const levelSize = queue.length;
9
10 for (let i = 0; i < levelSize; i++) {
11 const node = queue.shift();
12 levelMax = Math.max(levelMax, node.val);
13 if (node.left) queue.push(node.left);
14 if (node.right) queue.push(node.right);
15 }
16
17 result.push(levelMax);
18 }
19
20 return result;
21};
This JavaScript solution uses an array as a queue to implement a breadth-first search (BFS) of the tree, level by level. It identifies the largest value at each level and stores these in the result
array. JavaScript's shift()
method offers an easy way to dequeue elements from the front of the array.
The DFS approach involves recursively exploring each branch of the tree depth-first and leveraging the depth of recursion to determine the level of the tree. For each level not yet considered, the maximum value is initialized, or updated if a new larger value is found.
Time Complexity: O(n) where n is the number of nodes in the tree, since every node is visited once. Space Complexity: O(h) where h is the height of the tree due to recursion stack.
1import java.util.*;
This Java solution adopts a recursive DFS strategy. For each node, it utilizes the current recursion depth to determine the level for updating the maximum node value. New levels add an entry to the maxValues list, while existing levels update the maximum based on new node values.