-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path988.cpp
More file actions
35 lines (34 loc) · 1.07 KB
/
988.cpp
File metadata and controls
35 lines (34 loc) · 1.07 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
// Daily 17.4.2024
// 988. Smallest String Starting From Leaf
// https://leetcode.com/problems/smallest-string-starting-from-leaf/submissions/1234742888
/**
* 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 {
private:
void traverseDown(TreeNode* node, string& result, string acc){
acc.push_back(97+node->val);
if(!(node->left || node->right)){
reverse(acc.begin(), acc.end());
if(acc<result || result.empty()) result = acc;
}
else{
if(node->left) traverseDown(node->left, result, acc);
if(node->right) traverseDown(node->right, result, acc);
}
}
public:
string smallestFromLeaf(TreeNode* root) {
string res;
traverseDown(root, res, "");
return res;
}
};