선택은 나의 것

[LeetCode] 515. Find Largest Value in Each Tree Row (cpp) 본문

☽ Algorithm/LeetCode

[LeetCode] 515. Find Largest Value in Each Tree Row (cpp)

Algoribi 2021. 2. 19. 11:21

문제

LeetCode 515 : leetcode.com/problems/find-largest-value-in-each-tree-row/

 

Find Largest Value in Each Tree Row - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

접근

주어진 트리의 레벨(깊이) 별로 가장 큰 값을 반환해주는 문제이다.

DFS를 통해 트리를 탐색하며 레벨별로 큰 값을 만날 때마다 값을 갱신해준다.

코드

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> ans;
    int chk = 0;
    void dfs(TreeNode* root, int counter) {
        if (root == NULL)
            return ;
        else if (chk -1 < counter) {
            ans.push_back(root->val);
            chk++;
        } else if (ans[counter] < root->val)
            ans[counter] = root->val;
        
        dfs(root->left, counter+1);
        dfs(root->right, counter+1);
    }
    vector<int> largestValues(TreeNode* root) {
        dfs(root, 0);
        return ans;
    }
};

 

깃 허브 주소 : https://github.com/algoribi/algorithm-study

'☽ Algorithm > LeetCode' 카테고리의 다른 글

[LeetCode] 513. Find Bottom Left Tree Value (cpp)  (0) 2021.02.19
Comments