DFS+回溯专题11 - leetcode257. Binary Tree Paths/93. Restore IP Addresses

本文探讨了两种算法问题:一是寻找二叉树的所有根节点到叶节点路径,二是从数字串中恢复所有可能的有效IP地址组合。通过深度优先搜索(DFS)策略,实现了二叉树路径的遍历,并考虑了IP地址的有效性和格式规范。

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

257. Binary Tree Paths

题目描述

给定二叉树,返回所有根节点-叶节点路径。

例子

257

思想
截止条件:到达叶节点(not root.left and not root.right)

解法

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

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

精简

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        if not root:
            return []
        if not root.left and not root.right:
            return [str(root.val)]
        paths = self.binaryTreePaths(root.left) + self.binaryTreePaths(root.right)
        return [str(root.val) + '->' + path for path in paths]
93. Restore IP Addresses

题目描述

给定只包含数字的字符串,返回所有可能有效的IP地址组合。

例子

Input: “25525511135”
Output: [“255.255.11.135”, “255.255.111.35”]

思想

合法的IP地址由四个0到255的整数组成。且多个数字时要注意首位不能为0,因为01.0.0.0 这样的IP是不符合规范的。

每位可能的数字位数是1-3位。所以,遍历所有可能的位数(1位、2位、3位且不超过255)。
[截止条件]:刚好遍历完,且4位,存储;到达4位但没有遍历完,直接return。

解法

class Solution(object):
    def restoreIpAddresses(self, s):
        """
        :type s: str
        :rtype: List[str]
        """
        res = []
        self.dfs(s, [], res)
        return res
        
    def dfs(self, s, temp, res):
        if not s:
            if len(temp) == 4:
                res.append('.'.join(temp))
            return
        if len(temp) == 4:
            return
        
        self.dfs(s[1:], temp + [s[0]], res)
        if s[0] != '0':
            if len(s) >= 2:
                self.dfs(s[2:], temp + [s[:2]], res)
            if len(s) >= 3 and int(s[:3]) <= 255:
                self.dfs(s[3:], temp + [s[:3]], res)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值