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 分钟前
【构造 前缀和】P8902 [USACO22DEC] Range Reconstruction S|普及+
c++·算法·前缀和·洛谷·构造
摸鱼仙人~7 分钟前
动态规划求解 20 个通用模板
算法·动态规划
记忆多12 分钟前
c++内联函数
算法
仟濹25 分钟前
【算法打卡day20(2026-03-12 周四)算法/技巧:哈希表,双指针,字符串交换处理】5个题
数据结构·算法·散列表
陌夏26 分钟前
双指针与滑动窗口
算法
敲代码的嘎仔30 分钟前
Java后端开发——Redis面试题汇总
java·开发语言·redis·学习·缓存·面试·职场和发展
MicroTech202535 分钟前
MLGO微算法科技,推出革命性量子算法ANQITE,推动量子计算新时代
科技·算法·量子计算
ErizJ1 小时前
面试 | 操作系统
linux·面试·职场和发展·操作系统·os
17(无规则自律)1 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode·哈希算法
样例过了就是过了1 小时前
LeetCode热题100 子集
数据结构·c++·算法·leetcode·dfs