|
| 1 | +// Source : https://leetcode.com/problems/smallest-string-starting-from-leaf/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2019-02-05 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * Given the root of a binary tree, each node has a value from 0 to 25 representing the letters 'a' to |
| 8 | + * 'z': a value of 0 represents 'a', a value of 1 represents 'b', and so on. |
| 9 | + * |
| 10 | + * Find the lexicographically smallest string that starts at a leaf of this tree and ends at the root. |
| 11 | + * |
| 12 | + * (As a reminder, any shorter prefix of a string is lexicographically smaller: for example, "ab" is |
| 13 | + * lexicographically smaller than "aba". A leaf of a node is a node that has no children.) |
| 14 | + * |
| 15 | + * Example 1: |
| 16 | + * |
| 17 | + * Input: [0,1,2,3,4,3,4] |
| 18 | + * Output: "dba" |
| 19 | + * |
| 20 | + * Example 2: |
| 21 | + * |
| 22 | + * Input: [25,1,3,1,3,0,2] |
| 23 | + * Output: "adz" |
| 24 | + * |
| 25 | + * Example 3: |
| 26 | + * |
| 27 | + * Input: [2,2,1,null,1,0,null,0] |
| 28 | + * Output: "abc" |
| 29 | + * |
| 30 | + * Note: |
| 31 | + * |
| 32 | + * The number of nodes in the given tree will be between 1 and 1000. |
| 33 | + * Each node in the tree will have a value between 0 and 25. |
| 34 | + * |
| 35 | + ******************************************************************************************************/ |
| 36 | +/** |
| 37 | + * Definition for a binary tree node. |
| 38 | + * struct TreeNode { |
| 39 | + * int val; |
| 40 | + * TreeNode *left; |
| 41 | + * TreeNode *right; |
| 42 | + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} |
| 43 | + * }; |
| 44 | + */ |
| 45 | +class Solution { |
| 46 | +public: |
| 47 | + string smallestFromLeaf(TreeNode* root) { |
| 48 | + string str, result="{"; //'z'+1; |
| 49 | + smallestFromLeafHelper(root, str, result); |
| 50 | + return result; |
| 51 | + } |
| 52 | + |
| 53 | + void smallestFromLeafHelper(TreeNode* root, string str, string& result) { |
| 54 | + if (root->left == NULL && root->right == NULL) { |
| 55 | + str.insert(0, 1, char(root->val+'a')); |
| 56 | + result = min(result, str); |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + str.insert(0, 1, char(root->val+'a')); |
| 61 | + |
| 62 | + if (root->left) { |
| 63 | + smallestFromLeafHelper(root->left, str, result); |
| 64 | + } |
| 65 | + if (root->right) { |
| 66 | + smallestFromLeafHelper(root->right, str, result); |
| 67 | + } |
| 68 | + } |
| 69 | +}; |
0 commit comments