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
相关推荐
衡石科技11 分钟前
Data_Agent记忆机制与经验复用衡石分析智能体会话记忆与长期学习技术解析
人工智能·科技·学习·算法·企业级bi
shirsl2 小时前
算法 Day 2 滑动窗口 + 栈 / 单调栈
开发语言·python·算法
土司大王2 小时前
LeetCode hot100 回溯专题总结:Java 通用模板、决策树模型
java·算法·leetcode·决策树
2601_962218613 小时前
万象生鲜系统订单全生命周期状态同步技术实现业务可视
大数据·数据库·人工智能·python·算法
那年窗外下的雪.3 小时前
AIDC 学习日志|第 22 天|All-Active/Single-Active 故障演练设计
服务器·网络·学习·算法·哈希算法
wzdark4 小时前
基于启发式搜索的最优路径规划算法研究4
算法
l1t4 小时前
用superpi、tinypi、tpi等工具计算圆周率的比较
c语言·算法
小智老师PMP4 小时前
2026PMP第八版新纲深度解读|从流程管控到价值交付,核心考点全迭代
人工智能·职场和发展·软件工程·制造·敏捷流程
a187927218314 小时前
【算法】链表(二):链表上的双指针——变速、异链与定距,和一份路程账本
数据结构·算法·leetcode·链表·go·指针·环形链表
2601_958352905 小时前
还要写 AEC 算法?0 代码 + 6 个引脚,F-18 让通话清晰度提升 300%
人工智能·算法·降噪消回音