Skip to content

Commit dfff79a

Browse files
authored
Create find-largest-value-in-each-tree-row.cpp
1 parent d2347b6 commit dfff79a

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// Time: O(n)
2+
// Space: O(h)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
14+
class Solution {
15+
public:
16+
vector<int> largestValues(TreeNode* root) {
17+
vector<int> result;
18+
largestValuesHelper(root, 0, &result);
19+
return result;
20+
}
21+
private:
22+
void largestValuesHelper(TreeNode* root, int depth, vector<int> *result) {
23+
if (!root) {
24+
return;
25+
}
26+
if (depth == result->size()) {
27+
result->emplace_back(root->val);
28+
} else {
29+
(*result)[depth] = max((*result)[depth], root->val);
30+
}
31+
largestValuesHelper(root->left, depth + 1, result);
32+
largestValuesHelper(root->right, depth + 1, result);
33+
}
34+
};
35+
36+
// Time: O(n)
37+
// Space: O(n)
38+
class Solution2 {
39+
public:
40+
vector<int> largestValues(TreeNode* root) {
41+
if (!root) {
42+
return {};
43+
}
44+
vector<int> result;
45+
vector<TreeNode*> curr, next;
46+
curr.emplace_back(root);
47+
while (!curr.empty()) {
48+
int max_val = numeric_limits<int>::min();
49+
next.clear();
50+
for (const auto& node : curr) {
51+
max_val = max(max_val, node->val);
52+
if (node->left) {
53+
next.emplace_back(node->left);
54+
}
55+
if (node->right) {
56+
next.emplace_back(node->right);
57+
}
58+
}
59+
result.emplace_back(max_val);
60+
swap(curr, next);
61+
}
62+
return result;
63+
}
64+
};

0 commit comments

Comments
 (0)