Skip to content

Commit b3bd9c2

Browse files
committed
515. Find Largest Value in Each Tree Row
1 parent 64f3f35 commit b3bd9c2

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
//Runtime: 12 ms
2+
class Solution {
3+
public:
4+
vector<int> largestValues(TreeNode* root) {
5+
6+
vector<int>res;
7+
8+
if(!root)
9+
return res;
10+
11+
vector<int>temp;
12+
queue<pair<int, TreeNode*> >Q;
13+
Q.push(make_pair(0,root));
14+
15+
int maxlvl = 0;
16+
17+
while(!Q.empty())
18+
{
19+
pair<int,TreeNode*> t = Q.front();
20+
Q.pop();
21+
22+
if(t.first > maxlvl)
23+
{
24+
maxlvl++;
25+
if(temp.size() > 0)
26+
{
27+
int maxa = INT_MIN;
28+
for(int a:temp)
29+
maxa = max(a, maxa);
30+
31+
temp.clear();
32+
res.push_back(maxa);
33+
}
34+
35+
}
36+
temp.push_back(t.second->val);
37+
if(t.second->left)
38+
Q.push(make_pair(t.first+1, t.second->left));
39+
40+
if(t.second->right)
41+
Q.push(make_pair(t.first+1, t.second->right));
42+
}
43+
44+
if(temp.size() > 0)
45+
{
46+
int maxa = INT_MIN;
47+
for(int a:temp)
48+
maxa = max(maxa, a);
49+
res.push_back(maxa);
50+
}
51+
52+
return res;
53+
}
54+
};

0 commit comments

Comments
 (0)