Recursive - string or list?

1 篇文章 0 订阅
1 篇文章 0 订阅
文章讨论了两种在LeetCode257题(二叉树路径)中实现递归解法的方式:使用字符串和列表。字符串方法在递归过程中不需要删除字符,而列表方法需要在回溯时手动弹出元素以保持正确路径。两种方法都采用深度优先搜索(DFS)策略,最终将所有可能的路径转化为字符串并返回。
摘要由CSDN通过智能技术生成

Problem Description

Leetcode 257. Binary Tree Paths

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
  • When we use string, we do not need to delete characters when recursive, the address of string will be the older one automatically.
  • When we use list, we need to pop after invokig function itself, to achieve the effect of recursive.

Recursive with string (better)

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

Recursive with list

class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """

        paths = []
        def dfs(node, path):
            if not node:
                return
            path.append(node.val)
            if not node.left and not node.right:
                pathStr = ""
                if path:
                    pathStr = str(path[0])
                for index in range(1, len(path)):
                    pathStr += "->" + str(path[index])
                paths.append(pathStr)
            dfs(node.left, path)
            dfs(node.right, path)
            path.pop() # Need This Step!!!
        dfs(root, [])
        return paths
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值