Max Per Level
Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.
Description
Given a binary tree, write a method to return an array containing the largest (by value) node values at each level. In other words, we're looking for the max per level.

So for instance, given the following binary tree, we'd get [2, 7, 9] if the method grabbed the correct maxes.
/*
2
/ \
3 7
/ \ \
5 8 9
*/
maxValPerLevel(root);
// [2, 7, 9]
Assuming the standard tree node definition of:
function Node(val) {
this.val = val;
this.left = this.right = null;
}
Can you fill it out via the following function signature?
function maxValPerLevel(root) {
// if (!root) { return []; }
return;
};
Constraints
- The number of nodes in the given tree <=
100000 - The nodes will always contain integer values between
-1000000000and1000000000 - Expected time complexity :
O(n) - Expected space complexity :
O(n)
```js
function Node(val) {
this.val = val;
this.left = this.right = null;
}
function maxValPerLevel(root) {
// Fill in this method
return root;
}
// const root = new Node(2);
// root.left = new Node(3);
// root.right = new Node(7);
// root.left.left = new Node(5);
// root.left.right = new Node(8);
// root.right.right = new Node(9);
// console.log(maxValPerLevel(root));
```
CONTINUE WITH ALGODAILY PREMIUM
Keep going with the complete tutorial.
Unlock the remaining explanations and exercises, alongside the full learning library.
Explore Premium →