mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 09:59:41 +01:00
cpp: add «513. Find Bottom Left Tree Value»
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
aabf7eda27
commit
482a94aa73
1 changed files with 42 additions and 0 deletions
42
cpp/find-bottom-left-tree-value.cpp
Normal file
42
cpp/find-bottom-left-tree-value.cpp
Normal file
|
@ -0,0 +1,42 @@
|
||||||
|
#include <cassert>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
|
||||||
|
#ifdef _MF_TEST
|
||||||
|
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) {}
|
||||||
|
};
|
||||||
|
#endif
|
||||||
|
|
||||||
|
class Solution {
|
||||||
|
void find_bottom_left(std::map<int, std::optional<int>> &view, int y,
|
||||||
|
TreeNode *node) {
|
||||||
|
if (node == nullptr) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto &leftmost = view[y];
|
||||||
|
if (!leftmost.has_value()) {
|
||||||
|
leftmost = std::make_optional(node->val);
|
||||||
|
}
|
||||||
|
|
||||||
|
find_bottom_left(view, y - 1, node->left);
|
||||||
|
find_bottom_left(view, y - 1, node->right);
|
||||||
|
}
|
||||||
|
|
||||||
|
public:
|
||||||
|
int findBottomLeftValue(TreeNode *root) {
|
||||||
|
assert(root != nullptr);
|
||||||
|
|
||||||
|
std::map<int, std::optional<int>> leftview;
|
||||||
|
|
||||||
|
find_bottom_left(leftview, 0, root);
|
||||||
|
return leftview.begin()->second.value();
|
||||||
|
}
|
||||||
|
};
|
Loading…
Reference in a new issue