-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0988-smallest-string-starting-from-leaf.cpp
More file actions
52 lines (44 loc) · 1.42 KB
/
0988-smallest-string-starting-from-leaf.cpp
File metadata and controls
52 lines (44 loc) · 1.42 KB
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
#include <string>
#include <algorithm>
using namespace std;
// 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:
void find_depth(TreeNode *curr, int level, int *max) {
if (!curr)
return;
*max = std::max(level, *max);
find_depth(curr->left, level + 1, max);
find_depth(curr->right, level + 1, max);
}
bool smallest_from_leaf(TreeNode *curr, string curr_str, string *min) {
if (!curr)
return true;
bool l = smallest_from_leaf(curr->left, curr_str + (char)('a' + curr->val), min);
bool r = smallest_from_leaf(curr->right, curr_str + (char)('a' + curr->val), min);
if (l && r) {
curr_str += (char)('a' + (char)curr->val);
std::reverse(curr_str.begin(), curr_str.end());
*min = std::min(*min, curr_str);
}
return false;
}
string smallestFromLeaf(TreeNode* root) {
int level = 1;
find_depth(root, 1, &level);
string min;
for (int i = 1; i <= level; ++i) {
min += "z";
}
smallest_from_leaf(root, "", &min);
return min;
}
};