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
相关推荐
剪一朵云爱着3 小时前
力扣81. 搜索旋转排序数组 II
算法·leetcode·职场和发展
报错小能手5 小时前
刷题日常 5 二叉树最大深度
算法
Greedy Alg6 小时前
LeetCode 84. 柱状图中最大的矩形(困难)
算法
im_AMBER6 小时前
Leetcode 52
笔记·学习·算法·leetcode
小欣加油6 小时前
leetcode 946 验证栈序列
c++·算法·leetcode·职场和发展
包饭厅咸鱼6 小时前
PaddleOCR----制作数据集,模型训练,验证 QT部署(未完成)
算法
无敌最俊朗@7 小时前
C++ 并发与同步速查笔记(整理版)
开发语言·c++·算法
王哈哈^_^7 小时前
【完整源码+数据集】课堂行为数据集,yolo课堂行为检测数据集 2090 张,学生课堂行为识别数据集,目标检测课堂行为识别系统实战教程
人工智能·算法·yolo·目标检测·计算机视觉·视觉检测·毕业设计
测试19987 小时前
Appium使用指南与自动化测试案例详解
自动化测试·软件测试·python·测试工具·职场和发展·appium·测试用例