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
相关推荐
fengfuyao98524 分钟前
基于MATLAB实现任意平面太阳辐射量计算
算法·matlab·平面
放荡不羁的野指针42 分钟前
leetcode150题-字符串
数据结构·算法·leetcode
苦藤新鸡1 小时前
4.移动零
c++·算法·力扣
hetao17338371 小时前
2026-01-04~06 hetao1733837 的刷题笔记
c++·笔记·算法
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——存在重复元素Ⅱ
算法·leetcode·哈希算法·散列表·结构与算法
Boilermaker19921 小时前
[算法基础] DFS
算法
bubiyoushang8881 小时前
MATLAB比较SLM、PTS和Clipping三种算法对OFDM系统PAPR的抑制效果
数据结构·算法·matlab
cg50171 小时前
力扣数据库——组合两个表
sql·算法·leetcode
六边形战士DONK1 小时前
[强化学习杂记] 从数学角度理解贝尔曼最优公式为什么是greedy?
算法
C雨后彩虹1 小时前
计算误码率
java·数据结构·算法·华为·面试