1
/**
2
* Definition for a binary tree node.
3
* struct TreeNode {
4
* int val;
5
* TreeNode *left;
6
* TreeNode *right;
7
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
10
* right(right) {}
11
* };
12
*/
13
class Solution {
14
public:
15
string res;
16
void solve(TreeNode *root, string cur) {
17
if (!root) return;
18
cur.push_back((char)('a' + root->val)); // converting integer to corresponding characer
19
if (!root->left and !root->right) {
20
// reversing the string since it is computed from root to leaf, but we
21
// need viceversa
22
reverse(cur.begin(), cur.end());
23
if (res == "" or cur < res) res = cur; // updating the result based on lexicographical order
24
return;
25
}
26
solve(root->left, cur);
27
solve(root->right, cur);
28
return;
29
}
30
string smallestFromLeaf(TreeNode *root) {
31
if (!root) return "";
32
solve(root, "");
33
return res;
34
}
35
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0