1302. Deepest Leaves Sum**

1302. Deepest Leaves Sum**

https://leetcode.com/problems/deepest-leaves-sum/

题目描述

Given a binary tree, return the sum of values of its deepest leaves.

Example 1:

Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15

Constraints:

  • The number of nodes in the tree is between 1 and 10^4.
  • The value of nodes is between 1 and 100.

C++ 实现 1

使用递归还是有点麻烦, 发现用迭代更为方便, 使用层序遍历. 使用 sum 将每一层的叶子节点进行加和. 如果进入到新的一层, 那么 sum 要先进行清零操作.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int deepestLeavesSum(TreeNode* root) {
        if (!root) return 0;
        queue<TreeNode*> q;
        q.push(root);
        int sum = 0;
        while (!q.empty()) {
            auto size = q.size();
            // 当进入新的 level, sum 清零
            sum = 0;
            while (size --) {
                auto r = q.front();
                q.pop();
                if (r->left) q.push(r->left);
                if (r->right) q.push(r->right);
                if (!r->left && !r->right) sum += r->val;
            }
        }
        return sum;
    }
};

C++ 实现 2

(20210312 更新) 这题也可以用递归来做: 思路是使用 max_depth 记录最大的深度, 用 depth 记录当前的深度. 那么如果访问到某节点, 其 depth 大于 max_depth 时, 说明目前该节点是更深的, 因此要更新 max_depth, 累加和 sum 此时要清零. 之后如果再遇到深度等于 max_depth 的节点, 就将其值加入到 sum 中.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    int max_depth = 0, sum = 0;
    void dfs(TreeNode *root, int depth) {
        if (!root) return;
        if (depth > max_depth) {
            max_depth = depth;
            sum = 0;
        }
        if (depth == max_depth) sum += root->val;
        dfs(root->left, depth + 1);
        dfs(root->right, depth + 1);
    }
public:
    int deepestLeavesSum(TreeNode* root) {
        dfs(root, 0);
        return sum;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值