-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path515-Find-Largest-Value-in-Each-Tree-Row.c
50 lines (50 loc) · 1.17 KB
/
515-Find-Largest-Value-in-Each-Tree-Row.c
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* largestValues(struct TreeNode* root, int* returnSize) {
int *result = (int*)malloc(100000 * sizeof(int));
struct TreeNode* queue[100000];
int head = 0, tail = -1, sentinel = 0;
int max;
*returnSize = 0;
if (NULL != root)
{
queue[++tail] = root;
max = queue[head]->val;
}
while (head <= tail)
{
if (NULL != queue[head]->left)
{
queue[++tail] = queue[head]->left;
}
if (NULL != queue[head]->right)
{
queue[++tail] = queue[head]->right;
}
if (max < queue[head]->val)
{
max = queue[head]->val;
}
if (head == sentinel)
{
result[(*returnSize)++] = max;
sentinel = tail;
if (head < tail)
{
max = queue[head + 1]->val;
}
}
head++;
}
return result;
}