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
相关推荐
sali-tec39 分钟前
C# 基于halcon的视觉工作流-章42-手动识别文本
开发语言·人工智能·算法·计算机视觉·c#·ocr
SandySY1 小时前
品三国谈人性
算法·架构
小欣加油1 小时前
leetcode 62 不同路径
c++·算法·leetcode·职场和发展
夏鹏今天学习了吗1 小时前
【LeetCode热题100(38/100)】翻转二叉树
算法·leetcode·职场和发展
夏鹏今天学习了吗1 小时前
【LeetCode热题100(36/100)】二叉树的中序遍历
算法·leetcode·职场和发展
DTS小夏1 小时前
算法社Python基础入门面试题库(新手版·含答案)
python·算法·面试
Mr.Ja2 小时前
【LeetCode热题100】No.11——盛最多水的容器
算法·leetcode·贪心算法·盛水最多的容器
冷徹 .2 小时前
2024ICPC区域赛香港站
数据结构·c++·算法
浅川.253 小时前
xtuoj string
开发语言·c++·算法
韩非3 小时前
if 语句对程序性能的影响
算法·架构