-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path515-find-largest-value-in-each-tree-row.cpp
64 lines (64 loc) · 1.61 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
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* 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> res;
if (root == NULL)
{
return res;
}
queue<TreeNode*> node_queue;
TreeNode* start = root;
TreeNode* end = root;
TreeNode* cur_end = NULL;
node_queue.push(root);
int cur_max = INT_MIN;
while (!node_queue.empty())
{
TreeNode* p = node_queue.front();
node_queue.pop();
if (p == start)
{
if (p->left != NULL)
{
start = p->left;
}
else if (p->right != NULL)
{
start = p->right;
}
else if (!node_queue.empty())
{
start = node_queue.front();
}
}
cur_max = max(cur_max, p->val);
if (p->left != NULL)
{
cur_end = p->left;
node_queue.push(p->left);
}
if (p->right != NULL)
{
cur_end = p->right;
node_queue.push(p->right);
}
if (p == end)
{
res.push_back(cur_max);
cur_max = INT_MIN;
end = cur_end;
cur_end = NULL;
}
}
return res;
}
};