C语言 | Leetcode C语言题解之第515题在每个树行中找最大值
题目:
题解:
#define MAX_NODE_SIZE 10001
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int* largestValues(struct TreeNode* root, int* returnSize) {
if (!root) {
*returnSize = 0;
return NULL;
}
int *res = (int *)malloc(sizeof(int) * MAX_NODE_SIZE);
int pos = 0;
struct TreeNode **queue = (struct TreeNode *)malloc(sizeof(struct TreeNode *) * MAX_NODE_SIZE);
int head = 0, tail = 0;
queue[tail++] = root;
while (head != tail) {
int len = tail - head;
int maxVal = INT_MIN;
while (len > 0) {
len--;
struct TreeNode *node = queue[head++];
maxVal = MAX(maxVal, node->val);
if (node->left) {
queue[tail++] = node->left;
}
if (node->right) {
queue[tail++] = node->right;
}
}
res[pos++] = maxVal;
}
*returnSize = pos;
free(queue);
return res;
}