-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0988_Smallest-String-Starting-From-Leaf.cpp
More file actions
41 lines (40 loc) · 1.12 KB
/
Copy path0988_Smallest-String-Starting-From-Leaf.cpp
File metadata and controls
41 lines (40 loc) · 1.12 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
/**
* 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<string> candidate;
string now;
string smallestFromLeaf(TreeNode* root) {
candidate.clear();
now = "";
traverse(root);
return *std::min_element(candidate.begin(),candidate.end());
}
void traverse(TreeNode* root) {
if (root == nullptr) {
candidate.push_back(now);
return;
} else {
char c = root->val + 'a';
string tmp = "";
tmp += c;
now.insert(0, tmp);
if (root->left)
traverse(root->left);
if (root->right)
traverse(root->right);
if (!root->left && !root->right)
candidate.push_back(now);
now.erase(0, 1);
}
}
};