层序遍历,使用链式队列
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct qNode {
struct TreeNode *node;
int deep;
struct qNode *next;
};
struct Queuee {
struct qNode *front;
struct qNode *rear;
};
void InQueuee(struct Queuee *q, struct TreeNode *node, int deep)
{
struct qNode *n = (struct Node *)malloc(sizeof(struct qNode));
n->node = node;
n->deep = deep;
n->next = NULL;
if (q->rear == NULL) {
q->front = n;
} else {
q->rear->next = n;
}
q->rear = n;
}
struct TreeNode *OutQueuee(struct Queuee *q, int *deep)
{
if (q->front == NULL) {
return NULL;
}
struct TreeNode *node;
struct Node *n;
node = q->front->node;
*deep = q->front->deep;
n = q->front;
if (q->front != q->rear) {
q->front = q->front->next;
} else {
q->front = NULL;
q->rear = NULL;
}
free(n);
return node;
}
bool IsEmpty(struct Queuee *q)
{
if (q->front == NULL) {
return true;
}
return false;
}
int deepestLeavesSum(struct TreeNode* root){
if (root == NULL) {
return 0;
}
int deep = 0;
int temp;
int ans = 0;
struct TreeNode* node;
struct Queuee *head = (struct Queuee *)malloc(sizeof(struct Queuee));
head->front = NULL;
head->rear = NULL;
InQueuee(head, root, deep);
while (!IsEmpty(head)) {
node = OutQueuee(head, &temp);
if (node->left != NULL) {
InQueuee(head, node->left, temp + 1);
}
if (node->right != NULL) {
InQueuee(head, node->right, temp + 1);
}
if (temp == deep) {
ans += node->val;
} else {
deep++;
ans = node->val;
}
}
free(head);
return ans;
}