解题思路:
(1)先遍历求出最深的深度值
(2)再遍历一次,将最深的节点值相加
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int max = 0,sum = 0;
public:
void preorder(TreeNode *root,int h) {
if(root!=NULL) {
if(h>max) max = h;
preorder(root->left,h+1);
preorder(root->right,h+1);
}
}
void getsum(TreeNode *root,int h) {
if(root!=NULL) {
if(h==max) sum+=root->val;
getsum(root->left,h+1);
getsum(root->right,h+1);
}
}
int deepestLeavesSum(TreeNode* root) {
int h = 0;
preorder(root,h);
getsum(root,h);
return sum;
}
};