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;
    }
};
发布了352 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104552971