[988][中等][DFS] 从叶结点开始的最小字符串
最后更新于
最后更新于
输入:[0,1,2,3,4,3,4]
输出:"dba"输入:[25,1,3,1,3,0,2]
输出:"adz"输入:[2,2,1,null,1,0,null,0]
输出:"abc"# 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:
if root is None:
return ''
def dfs(node, path):
if node is None:
return path[::-1]
path = path.copy()
path.append(node.val)
left_path = dfs(node.left, path)
right_path = dfs(node.right, path)
if node.left is None:
return right_path
elif node.right is None:
return left_path
else:
len_left, len_right = len(left_path), len(right_path)
new_path = None
for i in range(min(len_left, len_right)):
if left_path[i] != right_path[i]:
new_path = left_path if left_path[i] < right_path[i] else right_path
break
if new_path is None:
new_path = left_path if len_left < len_right else right_path
return new_path
smallest = dfs(root, [])
return ''.join(chr(num + 97) for num in smallest)