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
相关推荐
wearegogog1236 分钟前
基于Q-learning的栅格地图路径规划MATLAB仿真程序
开发语言·算法·matlab
旖-旎9 分钟前
深搜练习(组合总和)(7)
c++·算法·深度优先·力扣
小O的算法实验室20 分钟前
2026年ASOC,基于人工势场的差分进化算法改进框架,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
爱学习的张大25 分钟前
具身智能论文精读(五):OpenVLA
人工智能·算法
逻辑驱动的ken1 小时前
Java高频面试场景题19
java·开发语言·面试·职场和发展·求职招聘
刘大猫.1 小时前
宝马发布全新AI智能座舱助手 能理解用户复杂出行需求
人工智能·算法·机器学习·ai·大模型·算力·ai智能座舱助手
如何原谅奋力过但无声2 小时前
【灵神高频面试题合集01-03】相向双指针、滑动窗口
数据结构·python·算法·leetcode
leoufung2 小时前
LeetCode 42:接雨水 —— 从“矩形法”到双指针的完整思考过程
java·算法·leetcode
_日拱一卒3 小时前
LeetCode:543二叉树的直径
算法·leetcode·职场和发展
汉克老师3 小时前
GESP2025年3月认证C++五级( 第一部分选择题(9-15))
c++·算法·高精度计算·二分算法·gesp5级·gesp五级