Leetcode 1030 Solution

This article provides solution to leetcode question 1030 (smallest-string-starting-from-leaf)

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

Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def smallestFromLeaf(self, root: TreeNode) -> str:
        self.ans = "~"

        def dfs(node, A):
            A.append(chr(node.val + ord('a')))

            if not node.left and not node.right:
                self.ans = min(self.ans, "".join(reversed(A)))
            else:
                if node.left:
                    dfs(node.left, A)
                if node.right:
                    dfs(node.right, A)
            A.pop(-1)

        dfs(root, [])

        return self.ans