Leetcode 988. Smallest String Starting From Leaf(python+cpp)

Leetcode 988. Smallest String Starting From Leaf

题目

Given the root of a binary tree, each node has a value from 0 to 25 representing the letters ‘a’ to ‘z’: a value of 0 represents ‘a’, a value of 1 represents ‘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.)
在这里插入图片描述

错误解法:

原本想利用129的方法,先将所有的path以字符串的形式添加到一个列表中,然后在进行后续处理,但是这题跟129有点区别,因为这题节点值可能会大于10,所以不能这样

def smallestFromLeaf(self, root: TreeNode) -> str:
        def getnumber(root,number):
            if not root.left and not root.right:
                numberlist.append(number+str(root.val))
                return
            if root.left:
                getnumber(root.left,number+str(root.val))
            if root.right:
                getnumber(root.right,number+str(root.val))
        if not root:
            return 0
        numberlist = []
        getnumber(root,'')
        _min = float('inf')
        
        for i in range(len(numberlist)):
            _sum = 0
            for char in numberlist[i]:
                _sum += int(char)
            if _min > _sum:
                index = i
                _min = _sum
        ans = ''
        for char in reversed(numberlist[index]):
            ans += chr(int(char) + ord('a'))
        return numberlist

正确解法:

还是采用129类似的方法,但是在recursion的时候直接挑选最小的值。既当前节点为叶子节点时,比较形成的新线路与当前最小值进行比较。在python中用ord函数来得到字母的acsii值,用chr函数来将ascii值转回字母。而在C++中,字母可以直接加上数字变成新的字母

class Solution:
    def smallestFromLeaf(self, root: TreeNode) -> str:
        self.ans = '~'
        def helper(root,curr):
            if root:
                curr += chr(root.val+ord('a'))
                if not root.left and not root.right:
                    self.ans = min(self.ans,curr[::-1])
                helper(root.left,curr)
                helper(root.right,curr)
        helper(root,'')
        return self.ans

时间复杂度:O(N *log N),N为节点个数,每个节点比较的复杂度为O(logN)
空间复杂度:O(N)

C++解法

class Solution {
public:
    string ans = "~";
    void helper(TreeNode* root, string curr){
        if(root!=NULL){
            curr.push_back('a' + root->val);
            if(root->left==NULL && root->right==NULL){
                reverse(curr.begin(),curr.end());
                ans = min(ans,curr);
            }
            helper(root->left,curr);
            helper(root->right,curr);
        }
    }
            
    string smallestFromLeaf(TreeNode* root) {
        string s= "";
        helper(root,s);
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值