-
Notifications
You must be signed in to change notification settings - Fork 0
/
515.hpp
58 lines (47 loc) · 1.03 KB
/
515.hpp
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
46
47
48
49
50
51
52
53
54
55
56
57
58
#ifndef LEETCODE_515_HPP
#define LEETCODE_515_HPP
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <numeric>
#include <stack>
#include <string>
#include "../common/leetcode.hpp"
using namespace std;
/*
You need to find the largest value in each row of a binary tree.
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
*/
class Solution {
public:
vector<int> largestValues(TreeNode *root) {
vector<int> result;
dfs(root, result, 0);
return result;
}
private:
void dfs(TreeNode *node, vector<int> &lvr, int depth) {
if (node == nullptr) {
return;
}
if (lvr.size() == depth) {
lvr.emplace_back(node->val);
} else {
lvr[depth] = max(lvr[depth], node->val);
}
dfs(node->left, lvr, depth + 1);
dfs(node->right, lvr, depth + 1);
}
};
#endif //LEETCODE_515_HPP