본문 바로가기

0/leetcode

988. Smallest String Starting From Leaf

반응형

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

 

Smallest String Starting From Leaf - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

# 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 smallestFromLeaf(self, root: TreeNode) -> str:
        
        self.ans = '~'
        
        def dfs(node, A) :
            
            if not node :
                return
            
            A.append(chr(node.val+ ord('a')))
            if not (node.left or node.right) :
                self.ans = min(self.ans, ''.join(reversed(A)))
            
            dfs(node.left, A)
            dfs(node.right, A)
            A.pop()
            
        dfs(root, [])
        return self.ans
    

정리 :

lexicographical order = 사전순으로 정렬.

파이썬 내장함수를 쓰면 따로 숫자로 변환하지 않아도 깔끔하게 비교 가능.

반응형

'0 > leetcode' 카테고리의 다른 글

207. Course Schedule  (0) 2020.09.08
41. First Missing Positive  (0) 2020.09.08
16. 3Sum Closest  (0) 2020.09.08
835. Image Overlap  (0) 2020.09.07
1305. All elements in two binary search trees  (0) 2020.09.06