首页 > 其他 > 详细

Leetcode 257. Binary Tree Paths

时间:2021-04-19 23:18:33      阅读:20      评论:0      收藏:0      [点我收藏+]

Description: Given the root of a binary tree, return all root-to-leaf paths in any order.

A leaf is a node with no children.

Link: 257. Binary Tree Paths

Examples:

Example 1:
技术分享图片
Input: root = [1,2,3,null,5]
Output: ["1->2->5","1->3"]

Example 2:
Input: root = [1]
Output: ["1"]

思路: 返回所有从root到叶子节点的路径,又是返回所有解,回溯法。

class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        self.res = []
        self.dfs(root, ‘‘)
        return self.res
    
    def dfs(self, root, path):
        if not root.left and not root.right:
            path += ->+str(root.val)
            self.res.append(path[2:])
            return
        if root.left:
            self.dfs(root.left, path+->+str(root.val))
        if root.right:
            self.dfs(root.right, path+->+str(root.val))

日期: 2021-04-19

Leetcode 257. Binary Tree Paths

原文:https://www.cnblogs.com/wangyuxia/p/14678410.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!