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
相关推荐
小石头 1008615 小时前
【Java】String类(超级详细!!!)
java·开发语言·算法
.柒宇.15 小时前
力扣hot100---42.接雨水(java版)
java·算法·leetcode
youngee1115 小时前
hot100-41验证二叉搜索树
算法
迈巴赫车主15 小时前
蓝桥杯20534爆破 java
java·数据结构·算法·职场和发展·蓝桥杯
坚持就完事了15 小时前
数据结构之链表
数据结构·python·算法·链表
c#上位机16 小时前
halcon图像去噪—均值滤波
图像处理·算法·均值算法·halcon
曾几何时`16 小时前
347. 前 K 个高频元素 分别使用sort和priority_queue 对哈希结构自定义排序
算法
小李小李快乐不已16 小时前
图论理论基础(3)
数据结构·c++·算法·图论
牙牙要健康16 小时前
【open3d】示例:自动计算点人脸点云模型面部朝向算法
人工智能·python·算法
youngee1116 小时前
hot100-41二叉搜索树中第K小的元素
算法