Leetcode之Deepest Leaves Sum

題目:

Given a binary tree, return the sum of values of its deepest leaves.

Example 1:

Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15

 

Constraints:

  • The number of nodes in the tree is between 1 and 10^4.
  • The value of nodes is between 1 and 100.

代碼:

/**
 * 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:
    map<int, int> m;
void helper(TreeNode* root,int level,int& maxl) {
    if (!root)return;
    m[level] += root->val;
    maxl = max(maxl, level);
    helper(root->left, level + 1,maxl);
    helper(root->right, level + 1,maxl);
}
int deepestLeavesSum(TreeNode* root) {
    if (!root)return 0;
    int maxl = 0;
    helper(root, 0, maxl);
    return m[maxl];
}

};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章