1302-中等-层数最深叶子节点的和

在这里插入图片描述
层序遍历,使用链式队列

/**
 * 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值