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
相关推荐
itzixiao39 分钟前
L1-051 打折(5分)[java][python]
java·python·算法
贾斯汀玛尔斯1 小时前
每天学一个算法--Aho–Corasick 自动机
java·linux·算法
re林檎1 小时前
八大排序算法(C++实现)
c++·算法·排序算法
淘气包海鸟1 小时前
雷达度量衡量
人工智能·算法·机器学习·信息与通信
睡觉就不困鸭1 小时前
第12天 多数元素
算法·哈希算法·散列表
cpp_25011 小时前
P2639 [USACO09OCT] Bessie‘s Weight Problem G
数据结构·算法·动态规划·题解·洛谷·背包dp
郝学胜-神的一滴2 小时前
[力扣 227] 双栈妙解表达式计算:从思维逻辑到C++实战,吃透反向波兰式底层原理
java·前端·数据结构·c++·算法
LDG_AGI2 小时前
【搜索引擎】Elasticsearch(六):向量搜索深度解析:从参数原理到混合查询实战
人工智能·深度学习·算法·elasticsearch·机器学习·搜索引擎
会编程的土豆2 小时前
【数据结构与算法】二叉树深度
算法·深度优先
knight_9___2 小时前
RAG面试篇9
java·人工智能·python·算法·agent·rag