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
|
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; } };
|