1.题目:
您需要在二叉树的每一行中找到最大的值。
示例:
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: [1, 3, 9]
2.代码:
/**
* 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().
*/
#define MAX(a,b) ((a)>(b)?(a):(b))
typedef struct TreeNode* Tree;
typedef struct{
Tree *array;
int front,rear;
}Queue;
int* largestValues(struct TreeNode* root, int* returnSize) {
*returnSize=0;
int *r=(int* )malloc(5000*sizeof(int));
if(!root)
return r;
Queue *q=(Queue *)malloc(sizeof(Queue));
q->front=-1;
q->rear=-1;
q->array=(Tree *)malloc(10000*sizeof(Tree));
q->array[++q->rear]=root;
int last=0,max=root->val; //max初始化为根
while(q->front<q->rear){
root=q->array[++q->front];
max=MAX(root->val,max); //这一行每一个与max比较
if(root->left)
q->array[++q->rear]=root->left;
if(root->right)
q->array[++q->rear]=root->right;
if(q->front==last){ //这一行最后一个
r[(*returnSize)++]=max;
//max=root->right->val;
max=INT_MIN; //max置为最小值,其实最好是下一行的一个值。
last=q->rear;
}
}
return r;
}
3.知识点:
BFS+怎么找每一行最后一个。