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
相关推荐
Giser探索家2 小时前
无人机桥梁巡检:以“空天地”智慧之力守护交通生命线
大数据·人工智能·算法·安全·架构·无人机
budingxiaomoli5 小时前
算法--滑动窗口(二)
算法
ID_180079054735 小时前
淘宝实时拍立淘按图搜索数据|商品详情|数据分析提取教程
算法·数据分析·图搜索算法
l1t5 小时前
Lua与LuaJIT的安装与使用
算法·junit·单元测试·lua·luajit
Emilia486.7 小时前
【Leetcode&nowcode】代码强化练习(二叉树)
算法·leetcode·职场和发展
墨染点香7 小时前
LeetCode 刷题【135. 分发糖果】
算法·leetcode·职场和发展
秋风战士7 小时前
通信算法之336 :3GPPMixed Mode Turbo Decoder
算法·matlab·fpga开发·信息与通信·基带工程
是那盏灯塔7 小时前
【算法】——动态规划之01背包问题
数据结构·c++·算法·动态规划
im_AMBER7 小时前
Leetcode 41
笔记·学习·算法·leetcode
jinmo_C++8 小时前
数据结构_深入理解堆(大根堆 小根堆)与优先队列:从理论到手撕实现
java·数据结构·算法