Find the Smallest String Starting From Leaf in Python Program ?

  Python Questions & Answers

Today we will read on this page – shortest string starting with leaf in Python

If we have the root of a binary tree, the value of each node is from 0 to 25 representing the letters ‘a’ to ‘z’ – the value of 0 represents ‘a’, the value of 1 ‘b’ represents’, and so on. We have to search lexicographically the shortest string that starts at the leaf of this tree and finishes at the root. So if it is like a tree –

Smallest String Starting From Leaf in Python

Then the result will be “adz” as is the sequence [0,3,25]

class Solution(object):
   def smallestFromLeaf(self, root):
      """
      :type root: TreeNode
      :rtype: str
      """
      self.ans = "~"
      self.dfs(root,[])
      return self.ans
   def dfs(self, node, A):
      if node:
         A.append(chr(node.val + ord('a')))
         if not node.left and not node.right:
            self.ans = min(self.ans, ''.join(reversed(A)))
            A.pop()
            return
         self.dfs(node.left,A)
         self.dfs(node.right,A)
         A.pop()
         return
Input
[25,1,3,1,3,0,2]
Result
"adz"

LEAVE A COMMENT