LeetCode 1302 层数最深叶子节点的和

题目描述链接:https://leetcode-cn.com/problems/deepest-leaves-sum/

解题思路:方法一:dfs  方法二:bfs。

方法一:采用dfs进行搜索,用一个数组来记录每个深度的叶子节点和,最后返回最大深度的叶子节点和即可。

LeetCode代码如下:

/**
 * 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 sum_depth[10005];
    int max_depth;
    int deepestLeavesSum(TreeNode* root) {
          int depth=1;
          dfs(root,depth);
          return sum_depth[max_depth];
    }
    void dfs(TreeNode* root,int depth){
        if(!root){
            return ;
        }
        sum_depth[depth]+=root->val;
        max_depth=max(max_depth,depth);
        dfs(root->left,depth+1);
        dfs(root->right,depth+1);
    }
};

 方法二:采用bfs进行搜索,需要队列作为辅助的数据结构,保存当前节点所扩展出的下一层节点。然后同样用辅助数组记录每一层的和,返回最后一层的和即可。

具体LeetCode实现代码如下:

/**
 * 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 sum_depth[10005];
    int max_depth;
    int deepestLeavesSum(TreeNode* root) {
          queue<TreeNode*>q;
          q.push(root);
          int len;
          TreeNode *p;
          int depth=1;
          sum_depth[depth]=root->val;
          while(!q.empty()){
               len=q.size();
               depth+=1;
               for(int i=0;i<len;++i){
                   p=q.front();
                   q.pop();
                   if(p->left){
                     q.push(p->left);
                     sum_depth[depth]+=p->left->val;
                   }
                    if(p->right){
                     q.push(p->right);
                     sum_depth[depth]+=p->right->val;
                   }
               }
          }
          return sum_depth[depth-1];
    }

  
};
原文地址:https://www.cnblogs.com/zzw-/p/13357875.html