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
相关推荐
少许极端9 分钟前
算法奇妙屋(四十三)-贪心算法学习之路10
学习·算法·贪心算法
算法鑫探25 分钟前
10个数下标排序:最大值、最小值与平均值(下)
c语言·数据结构·算法·排序算法·新人首发
样例过了就是过了30 分钟前
LeetCode热题100 爬楼梯
c++·算法·leetcode·动态规划
IronMurphy32 分钟前
【算法三十七】51. N 皇后
算法·深度优先
DoUfp0bgq34 分钟前
从直觉到算法:贝叶斯思维的技术底层与工程实现
算法
ThisIsMirror1 小时前
leetcode 452 Arrays.sort()排序整数溢出、Integer.compare(a[1], b[1])成功的问题
算法·leetcode
王老师青少年编程1 小时前
csp信奥赛c++之状压枚举
数据结构·c++·算法·csp·信奥赛·csp-s·状压枚举
wayz111 小时前
数据分析中的异常值处理:MAD
算法·数据挖掘·数据分析
飞Link1 小时前
LangGraph 核心架构解析:节点 (Nodes) 与边 (Edges) 的工作机制及实战指南
java·开发语言·python·算法·架构
Mr_Xuhhh1 小时前
深入理解二叉树:从数据结构到算法实战
数据结构·算法