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
相关推荐
m0_5474866630 分钟前
《智能计算》全套课件PDF(武汉工程大学)
算法·贝叶斯算法·智能计算
Shaoshing1 小时前
LeetCode100 32.最长有效括号
java·数据结构·leetcode
weixin_307779131 小时前
Jupyter SQL 表血缘分析并导出 Excel
开发语言·python·sql·算法·excel
Lazyafei1 小时前
560. 和为 K 的子数组
数据结构·算法
小白的高手之路1 小时前
【LeetCode 热题 100】240. 搜索二维矩阵 II|矩阵、二分查找、Z 字形查找(Python)
python·算法·leetcode·矩阵·力扣
geovindu1 小时前
python:DBSCAN
开发语言·后端·python·算法
劲夫学编程1 小时前
leetcode:最长连续序列
leetcode·最长连续序列
Tim_102 小时前
【LeetCode】 525. 连续数组
算法
小蒋学算法2 小时前
算法-将数据流变为多个不相交区间-TreeMap
算法
Mortalbreeze2 小时前
图论算法篇:A*、Floyd、Bellman-Ford、SPFA
数据结构·c++·算法