Find Largest Value In Each Tree Row Problem


Description

LeetCode Problem 515.

Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).

Example 1:

1
2
Input: root = [1,3,2,5,3,null,9]
Output: [1,3,9]

Example 2:

1
2
Input: root = [1,2,3]
Output: [1,3]

Example 3:

1
2
Input: root = [1]
Output: [1]

Example 4:

1
2
Input: root = [1,null,2]
Output: [1,2]

Example 5:

1
2
Input: root = []
Output: []

Constraints:

  • The number of nodes in the tree will be in the range [0, 10^4].
  • -2^31 <= Node.val <= 2^31 - 1


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
 * 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> ans;
        if (root == NULL)
            return ans;
        
        queue<TreeNode*> bfsQ;
        bfsQ.push(root);
        
        TreeNode* curr;
        int len;
        int max_node;

        while (!bfsQ.empty()) {
            len = bfsQ.size();
            max_node = bfsQ.front()->val;

            for (int i = 0; i < len; i ++) {
                curr = bfsQ.front(); 
                bfsQ.pop();

                if (curr != NULL) {
                    if (curr->val > max_node)
                        max_node = curr->val;
                    if (curr->left != NULL)
                        bfsQ.push(curr->left);
                    if (curr->right != NULL)
                        bfsQ.push(curr->right);
                }
            }

            ans.push_back(max_node);
        }

        return ans;
    }
};




Related Posts

Average Of Levels In Binary Tree Problem

LeetCode 637. Given the root of a binary tree, return...

Zuma Game Problem

LeetCode 488. You are playing a variation of the game...

Trapping Rain Water II Problem

LeetCode 407. Given an m x n integer matrix heightMap...

Pacific Atlantic Water Flow Problem

LeetCode 417. There is an m x n rectangular island...

N-Ary Tree Level Order Traversal Problem

LeetCode 429. Given an n-ary tree, return the level order...

Minimum Genetic Mutation Problem

LeetCode 433. A gene string can be represented by an...