Home LeetCode - 515. Find Largest Value in Each Tree Row
Post
Cancel

LeetCode - 515. Find Largest Value in Each Tree Row

515. Find Largest Value in Each Tree Row - medium

문제

You need to find the largest value in each row of a binary tree.

제한사항

입출력 예

1
2
3
4
5
6
7
8
9
10
Example :
Input: 

          1
         / \
        3   2
       / \   \  
      5   3   9 

Output: [1, 3, 9]

풀이

  • DFS, BFS
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
39
40
41
42
43
44
45
/**
 * 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:
    vector<int> largestValues(TreeNode* root) {
        if(!root)
            return {};
        
        vector<int> ans;
        // 트리의 각 depth를 key값 으로 가지고, 최대값을 value로 가지는 map           
        map<int, int> m;
        queue<pair<TreeNode*, int>> q;
        
        // BFS
        q.push({root, 0});
        while(!q.empty()){
            auto node = q.front();
            q.pop();
            
            // map의 key중에 현재 depth가 있으면 최대값 비교
            // map의 key중에 현재 depth가 없으면 현재 노드의 값을 저장
            if(m.find(node.second) != m.end())
                m[node.second] = max(m[node.second], node.first->val);
            else
                m[node.second] = node.first->val;
                
            if(node.first->left)
                q.push({node.first->left, node.second + 1});
            if(node.first->right)
                q.push({node.first->right, node.second + 1});
        }
        
        for(const auto& i : m)
            ans.push_back(i.second);
        
        return ans;
    }
};
This post is licensed under CC BY 4.0 by the author.