和104题一样
    方法一:宽度遍历(BFS)
    遇到问题:1、未及时弹出队列数据导致运行超时
    2、可以使用官方给的定义方式
    3、尽量使用emplace代替push
    image.png

    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
    8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10. * };
    11. */
    12. class Solution {
    13. public:
    14. int deepestLeavesSum(TreeNode* root) {
    15. if(root==NULL){
    16. return 0;
    17. }
    18. int result=0;
    19. int maxdep=-1;
    20. queue<pair<TreeNode*,int>>q;
    21. q.emplace(root,0);
    22. while(!q.empty()){
    23. TreeNode* head=q.front().first;
    24. int depth = q.front().second;
    25. q.pop();
    26. if(depth>maxdep){
    27. result=head->val;
    28. maxdep=depth;
    29. }
    30. else if(depth==maxdep){
    31. result+=head->val;
    32. }
    33. if(head->left){
    34. q.emplace(head->left,depth+1);
    35. }
    36. if(head->right){
    37. q.emplace(head->right,depth+1);
    38. }
    39. }
    40. return result;
    41. }
    42. };

    方法二:深度遍历递归(DFS),前序遍历,使节点记住自己所在层若为最深层节点则加入到result结果中

    1. class Solution {
    2. private:
    3. int result = 0;
    4. int maxdep=-1;
    5. public:
    6. void DFS(TreeNode*root,int depth){
    7. if(root==NULL){
    8. return;
    9. }
    10. if(depth>maxdep){
    11. maxdep=depth;
    12. result=root->val;
    13. }
    14. else if(depth==maxdep){
    15. result+=root->val;
    16. }
    17. DFS(root->left,depth+1);
    18. DFS(root->right,depth+1);
    19. }
    20. int deepestLeavesSum(TreeNode* root) {
    21. DFS(root,0);
    22. return result;
    23. }
    24. };