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
相关推荐
敲代码的嘎仔2 分钟前
力扣高频SQL基础50题详解
开发语言·数据库·笔记·sql·算法·leetcode·后端开发
小虎牙0079 分钟前
面试被问复杂度总懵?这篇指南帮你彻底搞清
算法
炜宏资料库1 小时前
国网最新:电力市场结算规则解读
职场和发展
knight_9___1 小时前
大模型project面试4
人工智能·python·深度学习·算法·面试·agent
l1t2 小时前
DeepSeek总结的欢迎来到 ORDER BY 丛林
数据库·算法
谙弆悕博士2 小时前
【附C源码】二叉搜索树的C语言实现
c语言·开发语言·数据结构·算法·二叉树·项目实战·数据结构与算法
宵时待雨2 小时前
回溯算法专题2:二叉树中的深搜
开发语言·数据结构·c++·笔记·算法·深度优先
刀法如飞2 小时前
JavaScript 数组去重的 20 种实现方式,学会用不同思路解决问题
前端·javascript·算法
洛水水2 小时前
【力扣100题】46.单词拆分
算法·leetcode·职场和发展
MicroTech20253 小时前
量子安全赋能协同智能,微算法科技(NASDAQ :MLGO)研发PQS-BFL后量子区块链联邦学习框架
科技·算法·安全