Skip to content

Commit 66e7636

Browse files
Create Smallest String Starting From Leaf.cpp
1 parent d5bfca8 commit 66e7636

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
//https://leetcode.com/problems/smallest-string-starting-from-leaf/description/?envType=daily-question&envId=2024-04-17
2+
3+
/**
4+
* Definition for a binary tree node.
5+
* struct TreeNode {
6+
* int val;
7+
* TreeNode *left;
8+
* TreeNode *right;
9+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
10+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
11+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
12+
* };
13+
*/
14+
class Solution {
15+
public:
16+
string smallestFromLeaf(TreeNode* root) {
17+
string ans;
18+
dfs(root, "", ans);
19+
return ans;
20+
}
21+
22+
void dfs(TreeNode* root, string path, string& ans) {
23+
if (!root) return;
24+
25+
path += char('a' + root->val);
26+
27+
if (!root->left && !root->right) {
28+
reverse(path.begin(), path.end());
29+
if (ans.empty() || path < ans) {
30+
ans = path;
31+
}
32+
reverse(path.begin(), path.end());
33+
}
34+
35+
dfs(root->left, path, ans);
36+
dfs(root->right, path, ans);
37+
}
38+
};

0 commit comments

Comments
 (0)