-
Notifications
You must be signed in to change notification settings - Fork 0
/
515. Find Largest Value in Each Tree Row.cpp
51 lines (49 loc) · 1.21 KB
/
515. 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
43
44
45
46
47
48
49
50
51
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#define pb push_back
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
queue<TreeNode*> q1;
queue<int> q2;
vector<int> vals;
if(root == NULL)
return vals;
q1.push(root);
q2.push(0);
int prev_level = 0, max_val = root->val;
while(!q1.empty()){
int l = q2.front();
TreeNode *node = q1.front();
if(l > prev_level){
vals.pb(max_val);
prev_level = l;
max_val = node->val;
}
else{
max_val = max(max_val, node->val);
}
if(node->left){
q1.push(node->left);
q2.push(l+1);
}
if(node->right){
q1.push(node->right);
q2.push(l+1);
}
q1.pop();
q2.pop();
if(q1.empty()){
vals.pb(max_val);
}
}
return vals;
}
};