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
相关推荐
测试老哥13 分钟前
白盒测试用例的设计
自动化测试·软件测试·python·测试工具·职场和发展·单元测试·测试用例
YuanDaima204830 分钟前
双指针基础原理与题目说明
数据结构·人工智能·python·算法·leetcode·手撕代码
别或许31 分钟前
5、高数----一元函数微分学的应用(一)几何应用
算法
wayz1141 分钟前
Day 5:KNN算法与相似K线匹配
人工智能·算法·机器学习
晨曦中的暮雨1 小时前
Java集合类型主要有哪些?以及各自原理
数据结构·算法
lixinnnn.1 小时前
01BFS:Three States
算法
晓纪同学1 小时前
EffctiveC++_第三章_资源管理
开发语言·c++·算法
水云桐程序员2 小时前
C语言编程基础,输入与输出
c语言·开发语言·算法
ZPC82102 小时前
MoveIt Servo 与自己编写的 Action Server 通信
人工智能·算法·机器人
jllllyuz2 小时前
采用核函数的极限学习机(KELM)MATLAB实现
算法