[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

猜你喜欢

转载自blog.csdn.net/w5688414/article/details/109265028