Home LeetCode - 1302. Deepest Leaves Sum
Post
Cancel

LeetCode - 1302. Deepest Leaves Sum

1302. Deepest Leaves Sum - medium

문제

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

제한사항

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

입출력 예

eample

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

풀이

  • Tree, DFS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
 * 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 deepestLeavesSum(TreeNode* root) {
        map<int, int> sumMap;
        stack<pair<TreeNode*, int>> s;
        
        s.push({root, 0});
        
	    // DFS로 트리의 깊이별 노드의 val값 합을 구함
        while(!s.empty()){
            auto node = s.top();
            s.pop();
            
            // 깊이별 합을 map에 저장
            // sumMap[현재 노드의 깊이] += 현재 노드의 값
            sumMap[node.second] += node.first->val;
                
            if(node.first->right){
                s.push({node.first->right, node.second + 1});
            }
            
            if(node.first->left){
                s.push({node.first->left, node.second + 1});
            }
        }
        
        return sumMap.rbegin()->second;
    }
};
This post is licensed under CC BY 4.0 by the author.