-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathFind_Largest_Value_in_Each_Tree_Row.cpp
42 lines (41 loc) · 1.11 KB
/
Find_Largest_Value_in_Each_Tree_Row.cpp
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> result;
if(!root) return result;
queue<pair<TreeNode*, int>> Q;
int currLevel = 0;
Q.push({root, currLevel});
int maxElem = root->val;
while(!Q.empty()) {
TreeNode* node = Q.front().first;
int value = node->val;
int level = Q.front().second;
if(level > currLevel) {
result.push_back(maxElem);
currLevel = level;
maxElem = value;
} else {
maxElem = max(maxElem, value);
}
Q.pop();
if(node->left) {
Q.push({node->left, level + 1});
}
if(node->right) {
Q.push({node->right, level + 1});
}
}
result.push_back(maxElem);
return result;
}
};