[LeetCode] Smallest String Starting From Leaf

988. Smallest String Starting From Leaf

You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters ‘a’ to ‘z’.

Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root.

As a reminder, any shorter prefix of a string is lexicographically smaller.

  • For example, “ab” is lexicographically smaller than “aba”.

A leaf of a node is a node that has no children.

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
/**
* 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 {
string res = "";
void helper(TreeNode* node, string& s) {
if(!node) return;
s.push_back(node->val + 'a');

if(!node->left and !node->right) {
string rs = s;
reverse(begin(rs), end(rs));
if(res == "") res = rs;
else res = min(res, rs);
} else {
helper(node->left, s);
helper(node->right, s);
}

s.pop_back();
}
public:
string smallestFromLeaf(TreeNode* root) {
helper(root, string() = "");
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/02/PS/LeetCode/smallest-string-starting-from-leaf/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.