lc257. Binary Tree Paths

博客围绕二叉树展开,给定一个二叉树,要求返回所有根到叶的路径。采用深度优先搜索(DFS)记录每条路径的数组来解决问题,并给出了Python3代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. Binary Tree Paths Easy

897

68

Favorite

Share Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

1 /
2 3
5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

思路:dfs 记录每条线的数组 代码:python3

class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        if not root: return []
        arr=[]
        def dfs(root,ar):
            subAr=ar[:]
            if not root:return
            if not root.left and not root.right:
                subAr.append(str(root.val))
                arr.append(subAr)
            else:
                subAr.append(str(root.val))            
                dfs(root.left,subAr)
                dfs(root.right,subAr)                
        dfs(root,[])
        result=[]
        for a in arr:
            result.append('->'.join(a))
        return result
复制代码

转载于:https://juejin.im/post/5d0b28d9f265da1ba431f363

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值