일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- network
- 법의학
- data structure
- 독서
- 문제풀이
- LeetCode
- 재테크/투자
- 운영체제
- Programmers
- swea
- db
- 프로그래머스
- Database
- algogritim
- 네트워크
- 백준
- SW Expert Academy
- c++
- language
- OS
- 자료구조
- 알고리즘
- algorithm
- 데이터베이스
- cs
- 감상문
- Computer Science
- D3
- BOJ
- D2
Archives
- Today
- Total
선택은 나의 것
[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;
}
};
'☽ Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode] 513. Find Bottom Left Tree Value (cpp) (0) | 2021.02.19 |
---|
Comments