Leetcode 257. Binary Tree Paths

Problem

Given the root of a binary tree, return all root-to-leaf paths in any order.

A leaf is a node with no children.

Algorithm

Use dfs search to save the path.

Code

python3 复制代码
# 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 binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        if not root:
            return []

        if not root.left and not root.right:
            return [str(root.val)]
        
        ans = []
        save = []
        def dfs(node: TreeNode, depth):
            if not node.left and not node.right:
                s = ""
                for i in range(depth):
                    s += str(save[i]) + "->"
                ans.append(s + str(node.val))
                return
            if len(save) <= depth:
                save.append(node.val)
            else:
                save[depth] = node.val
            if node.left:
                dfs(node.left, depth+1)
            if node.right:
                dfs(node.right, depth+1)

        dfs(root, 0)
        return ans
相关推荐
王老师青少年编程5 分钟前
csp信奥赛C++高频考点专项训练之贪心算法 --【排序贪心】:拼数
c++·算法·贪心·csp·信奥赛·排序贪心·拼数
炽烈小老头22 分钟前
【 每天学习一点算法 2026/04/21】螺旋矩阵
学习·算法
未来转换37 分钟前
基于A2A协议的生产应用实践指南(Java)
java·开发语言·算法·agent
谭欣辰1 小时前
AC自动机:多模式匹配的高效利器
数据结构·c++·算法
joker_sxj1 小时前
论文阅读-DeepSeek-mHC
论文阅读·算法
sheeta19981 小时前
LeetCode 每日一题笔记 日期:2026.04.21 题目:1722. 执行交换操作后的最小汉明距离
笔记·算法·leetcode
鲸渔2 小时前
【C++ 跳转语句】break、continue、goto 与 return
开发语言·c++·算法
AI科技星2 小时前
基于螺旋元逻辑的宇宙统一场论底层公理构建(乖乖数学)
算法·机器学习·数学建模·数据挖掘·量子计算
qiqsevenqiqiqiqi2 小时前
MC0550鱼肠剑试锋芒
数据结构·算法
仍然.2 小时前
算法题目---链表
数据结构·算法·链表