2024-12-25 Daily Challenge
Today I have done leetcode's December LeetCoding Challenge with cpp
.
December LeetCoding Challenge 25
Description
Find Largest Value in Each Tree Row
Given the root
of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
Example 1:
Input: root = [1,3,2,5,3,null,9] Output: [1,3,9]
Example 2:
Input: root = [1,2,3] Output: [1,3]
Constraints:
- The number of nodes in the tree will be in the range
[0, 104]
. -231 <= Node.val <= 231 - 1
Solution
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
if(!root) return {};
vector<int> answer;
queue<TreeNode *> q;
q.push(root);
while(q.size()) {
int sz = q.size();
int maximum = INT_MIN;
for(int _ = 0; _ < sz; ++_) {
auto current = q.front();
q.pop();
maximum = max(maximum, current->val);
if(current->left) {
q.push(current->left);
}
if(current->right) {
q.push(current->right);
}
}
answer.push_back(maximum);
}
return answer;
}
};
// Accepted
// 78/78 cases passed (0 ms)
// Your runtime beats 100 % of cpp submissions
// Your memory usage beats 26.8 % of cpp submissions (22.7 MB)