[leetcode] 988. Smallest String Starting From Leaf

Description

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

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 between 1 and 8500.
  2. Each node in the tree will have a value between 0 and 25.

分析

题目的意思是:给定一个二叉树,然后其节点对应字母,求叶子结点到根结点最小的字符串。这道题没什么比较好的思路,开始以为可以在遍历的时候进行剪枝呢。后面发现需要一个数组来记录已经遍历过的字符串,当遍历到叶子结点的时候比较先前得到的最小字符串,然后更新最小字符串。如果能够想到这个就能做出来,如果想不到,那就gg了,跟我一样,哈哈哈。

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def solve(self,root,A):
        if(root is None):
            return 
        A.append(chr(root.val+ord('a')))
        if(not root.left and not root.right):
            self.res=min(self.res,''.join(reversed(A)))
        self.solve(root.left,A)
        self.solve(root.right,A)
        A.pop()
        
    def smallestFromLeaf(self, root: TreeNode) -> str:
        self.res='~'
        self.solve(root,[])
        return self.res

参考文献

[LeetCode]solution

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值