1. 程式人生 > 實用技巧 >[LeetCode] 988. Smallest String Starting From Leaf 從葉結點開始的最小字串

[LeetCode] 988. Smallest String Starting From Leaf 從葉結點開始的最小字串


Given therootof a binary tree, each node has a value from0to25representing the letters'a'to'z': a value of0represents'a', a value of1represents'b', and so on.

Find 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.)

Example 1:

Input: [0,1,2,3,4,3,4]
Output: "dba"

Example 2:

Input: [25,1,3,1,3,0,2]
Output: "adz"

Example 3:

Input: [2,2,1,null,1,0,null,0]
Output: "abc"

Note:

  1. The number of nodes in the given tree will be between1
    and8500.
  2. Each node in the tree will have a value between0and25.

這道題給了一棵二叉樹,說是結點值上的數字對應一個字母,讓返回從葉結點到根結點的路徑可以組成的字串中按字母順序排列最小的那個。其實這道題的本質就是找二叉樹的路徑,跟之前那道 Binary Tree Paths 一樣,從葉結點往回找路徑不是很方便,這裡還是找從根結點到葉結點的路徑,在組成字串的時候,每次把字元加到前頭就可以了,得到的還是從葉結點到根結點的順序。這裡還是使用遞迴來做,結果 res 初始化為 ~,博主最喜歡用一個表情符號,這麼做的原因是其 ASCII 碼值是大於z的,所以可以當初始值。在遞迴函式中,首先判空,否則將當前字元加到 cur 的最前面,然後判斷若當前結點是葉結點,則用 cur 來更新結果 res,接下來對左右子結點分別呼叫遞迴函式即可,參見程式碼如下:


解法一:

class Solution {
public:
    string smallestFromLeaf(TreeNode* root) {
        string res = "~";
        helper(root, "", res);
        return res;
    }
    void helper(TreeNode* node, string cur, string& res) {
        if (!node) return;
        cur = string(1, node->val + 'a') + cur;
        if (!node->left && !node->right) {
            res = min(res, cur);
        }
        helper(node->left, cur, res);
        helper(node->right, cur, res);
    }
};

我們也可以稍微寫的簡潔一些,讓遞迴函式有返回值,遞迴函式中還要帶個引數,首先判空,若為空,則返回 ~。否則將當前字元加到結果 res 前面,然後判斷左右結點是否相同,其實就是判斷是否均為 null,也就是判斷是否是葉結點,是的話就返回 res,否則返回分別對左右子結點呼叫遞迴函式得到的較小值,參見程式碼如下:


解法二:

class Solution {
public:
    string smallestFromLeaf(TreeNode* root) {
        return helper(root, "");
    }
    string helper(TreeNode* node, string res) {
        if (!node) return "~";
        res = string(1, node->val + 'a') + res;
        return node->left == node->right ? res : min(helper(node->left, res), helper(node->right, res));
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/988


類似題目:

Sum Root to Leaf Numbers

Binary Tree Paths


參考資料:

https://leetcode.com/problems/smallest-string-starting-from-leaf/

https://leetcode.com/problems/smallest-string-starting-from-leaf/discuss/231102/C%2B%2B-3-lines

https://leetcode.com/problems/smallest-string-starting-from-leaf/discuss/231251/Java-2-Concise-DFS-codes-with-comment.


LeetCode All in One 題目講解彙總(持續更新中...)