1.题目要求:
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
2.代码块;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
//创建队列结构体
typedef struct queue{
struct TreeNode* data;
struct queue* next;
}queue_t;
//入队函数
void insert_tail(queue_t** head,struct TreeNode* data){
queue_t* newnode = (queue_t*)malloc(sizeof(queue_t));
newnode->data = data;
newnode->next = NULL;
if(*head == NULL){
*head = newnode;
return;
}
queue_t* tail = *head;
while(tail->next != NULL){
tail = tail->next;
}
tail->next = newnode;
}
//出队函数
struct TreeNode* pop(queue_t** head){
struct TreeNode* x = (*head)->data;
*head = (*head)->next;
return x;
}
int* largestValues(struct TreeNode* root, int* returnSize) {
if(root == NULL){
*returnSize = 0;
return NULL;
}
int max1 = 0;//记录每一行的最大值;
int* max = (int*)malloc(sizeof(int) * 1000);//放入每一行最大值的数组
int j = 0;
int nextcount = 0;//记录下一行的结点数;
int count = 1;
int size = 0;
queue_t* sequence = NULL;
insert_tail(&sequence,root);//给队列入队
size++;
int flag = 1;//记录第一次的最大数
while(size != 0){
for(int i = 0;i < count;i++){
struct TreeNode* temp = pop(&sequence);//出队
size--;
//然后判断每一行的最大值
if(flag == 1){
max1 = temp->val;
flag = 0;
}else if(flag == 0){
if(temp->val > max1){
max1 = temp->val;
}
}
if(temp->left != NULL){
//入队
insert_tail(&sequence,temp->left);
size++;
nextcount++;
}
if(temp->right != NULL){
//入队
insert_tail(&sequence,temp->right);
size++;
nextcount++;
}
}
count = nextcount;
nextcount = 0;
max[j] = max1;
j++;
flag = 1;
max1 = 0;//在记录每一行最大值变为零,以方便记录下一行的最大值;
}
*returnSize = j;
return max;
}