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
相关推荐
YGGP19 小时前
【Golang】LeetCode 42. 接雨水
算法·leetcode·职场和发展
仰泳的熊猫19 小时前
题目1466:蓝桥杯基础练习VIP-字符串对比
数据结构·c++·算法·蓝桥杯
Renhao-Wan19 小时前
Java算法实践(二):堆与PriorityQueue实战
java·数据结构·算法
每天要多喝水19 小时前
动态规划Day29:打家劫舍
算法·动态规划
IT猿手19 小时前
多目标鲸鱼优化算法(MOWOA)求解46个多目标函数及一个工程应用,包含四种评价指标,MATLAB代码
开发语言·算法·matlab
罗湖老棍子19 小时前
星际能量矩阵:树形 DP 的递归与非递归双解
算法·动态规划·dfs·bfs·树型dp·树型动态规划
@––––––19 小时前
力扣hot100—系列7-二分查找
数据结构·算法·leetcode
MicroTech202519 小时前
微算法科技(NASDAQ: MLGO)引入量子启发式算法与区块链融合的数据预测与安全传输方案
科技·算法·启发式算法
近津薪荼19 小时前
优选算法——前缀和(5):和为 K 的子数组
算法
你撅嘴真丑19 小时前
第九章-竞赛题目选讲-跳舞机
数据结构·算法