Bootstrap

LeetCode //C - 515. Find Largest Value in Each Tree Row

515. 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 , 1 0 4 ] [0, 10^4] [0,104].
  • − 2 31 < = N o d e . v a l < = 2 31 − 1 -2^{31} <= Node.val <= 2^{31} - 1 231<=Node.val<=2311

From: LeetCode
Link: 515. Find Largest Value in Each Tree Row


Solution:

Ideas:

1. Initialization:

  • Use a queue to store nodes at each level for level-order traversal.
  • Start by pushing the root node into the queue.

2. Traversal:

  • For each level, compute the number of nodes (levelSize) in that level.
  • Iterate through the nodes in the queue to process each node’s value, keeping track of the maximum value in that level.

3. Children:

  • If a node has left or right children, add them to the queue for the next level.

4. Result:

  • Add the maximum value for each level to the result vector.

5. Return:

  • Return the vector containing the largest values from each row.
Code:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> largestValues(TreeNode* root) {
        vector<int> result;
        if (!root) return result;

        queue<TreeNode*> q;
        q.push(root);

        while (!q.empty()) {
            int levelSize = q.size();
            int maxVal = INT_MIN;

            for (int i = 0; i < levelSize; ++i) {
                TreeNode* current = q.front();
                q.pop();

                maxVal = max(maxVal, current->val);

                if (current->left) q.push(current->left);
                if (current->right) q.push(current->right);
            }

            result.push_back(maxVal);
        }

        return result;
    }
};
;