The number of nodes in the tree is in the range [1, 8500].
0 <= Node.val <= 25
Solutions
Solution 1
Thinking
A leaf-to-root path is a string; we want the lexicographically smallest. At most \(8500\) nodes, so every root-to-leaf path can be enumerated. DFS pushes letters, and at a leaf the reversed path is compared with the answer; then the letter is popped.
1 2 3 4 5 6 7 8 910111213141516171819202122
# 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 = rightclassSolution:defsmallestFromLeaf(self,root:TreeNode)->str:ans=chr(ord('z')+1)defdfs(root,path):nonlocalansifroot:path.append(chr(ord('a')+root.val))ifroot.leftisNoneandroot.rightisNone:ans=min(ans,''.join(reversed(path)))dfs(root.left,path)dfs(root.right,path)path.pop()dfs(root,[])returnans
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcsmallestFromLeaf(root*TreeNode)string{ans:=""vardfsfunc(root*TreeNode,pathstring)dfs=func(root*TreeNode,pathstring){ifroot==nil{return}path=string('a'+root.Val)+pathifroot.Left==nil&&root.Right==nil{ifans==""||path<ans{ans=path}return}dfs(root.Left,path)dfs(root.Right,path)}dfs(root,"")returnans}