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
相关推荐
白白白小纯26 分钟前
每日算法day3—回文链表,链表分割
c语言·数据结构·算法·leetcode
城管不管44 分钟前
RabbitMQ死信队列
java·分布式·ai·面试·职场和发展·rabbitmq·agent
手写码匠1 小时前
华为云Flexus+DeepSeek征文|Dify 构建企业级联网搜索 Agent:查询改写、多源检索与引用溯源实战
人工智能·深度学习·算法·aigc
七夜zippoe1 小时前
DolphinDB 能耗统计分析实战:报表生成、同比环比与定额对比
人工智能·算法·dolphindb·报表生成·能耗统计·定额对比
软件测试媛1 小时前
软件测试面试问题汇总
功能测试·面试·职场和发展·压力测试
城管不管1 小时前
rabbitmq如何保证消息不丢失?解决方案又是什么?
开发语言·ai·面试·职场和发展·rabbitmq·php·agent
为啥全要学1 小时前
在大语言模型上使用 PPO 算法
人工智能·算法·语言模型
zander2582 小时前
35. 搜索插入位置:从边界语义理解二分查找
数据结构·算法·leetcode
汤愈韬2 小时前
模型求解算法
人工智能·算法·机器学习
Keven_112 小时前
算法札记:DP中的滚动数组
算法·滚动数组