LeetCode 1302. 层数最深叶子节点的和 Deepest Leaves Sum

地址 https://leetcode-cn.com/problems/deepest-leaves-sum/

题目描述
给你一棵二叉树,请你返回层数最深的叶子节点的和。

输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
输出:15

算法1
递归遍历 额外记录下层级 然后叶子放入一个容器 以层级排序 输出

/**
 * 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:
    vector<pair<int,int>> leaf;
    void dfs(TreeNode* root,int level){
         if(root == NULL) return ;
        if(root->left == NULL && root->right == NULL) {
            leaf.push_back({level,root->val});
        }

        dfs(root->left,level+1);
        dfs(root->right,level+1);
    }

    int deepestLeavesSum(TreeNode* root) {
        dfs(root,0);   
        sort(leaf.begin(),leaf.end());
        int retsum =0;
        int levellimit = leaf.back().first;
        for(int i= leaf.size()-1; i >=0 ;i--){
            if(leaf[i].first == levellimit){
                retsum += leaf[i].second;
            }else{
                break;
            }
        }
        return retsum;
    }
};
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/12118306.html