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
相关推荐
charlie11451419121 分钟前
从 0 开始的机器学习——NumPy 线性代数部分
开发语言·人工智能·学习·线性代数·算法·机器学习·numpy
执携1 小时前
算法 -- 冒泡排序
数据结构·算法
寻星探路2 小时前
【算法专题】滑动窗口:从“无重复字符”到“字母异位词”的深度剖析
java·开发语言·c++·人工智能·python·算法·ai
程序员小白条2 小时前
面试 Java 基础八股文十问十答第八期
java·开发语言·数据库·spring·面试·职场和发展·毕设
wen__xvn2 小时前
代码随想录算法训练营DAY14第六章 二叉树 part02
数据结构·算法·leetcode
Ka1Yan2 小时前
[数组] - 代码随想录(2-6)
数据结构·算法·leetcode
漫随流水3 小时前
leetcode算法(104.二叉树的最大深度)
数据结构·算法·leetcode·二叉树
机器学习之心HML3 小时前
鲸鱼算法(WOA)优化Kriging模型
算法
DYS_房东的猫3 小时前
《 C++ 零基础入门教程》第6章:模板与 STL 算法 —— 写一次,用万次
开发语言·c++·算法
Tim_103 小时前
【算法专题训练】37、前缀树&二叉树
算法