/**
* 给你一棵二叉树,请你返回层数最深的叶子节点的和。
**/
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/**
1
/ 2 3
/ \ 4 5 6
/ 7 8
**/
class Solution {
private:
int maxdepth=0;//树的最大深度
int sum=0;//树的最大深度的结点值的和。
public:
void DFS(TreeNode* node,int depth){
if(!node->left&&!node->right){
if(depth>maxdepth){
sum=node->val;
maxdepth=depth;
}else if(depth==maxdepth){
sum+=node->val;
}
return;
}
if(node->left){
DFS(node->left,depth+1);
}
if(node->right){
DFS(node->right,depth+1);
}
}
int deepestLeavesSum(TreeNode* root) {
if(root){
DFS(root,1);
}
return sum;
}
};
原文:https://www.cnblogs.com/GarrettWale/p/12346968.html