Python | Leetcode Python题解之第337题打家劫舍III

题目:

题解:

python 复制代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def rob(self, root: TreeNode) -> int:
        def _rob(root):
            if not root: return 0, 0  # 偷,不偷

            left = _rob(root.left)
            right = _rob(root.right)
            # 偷当前节点, 则左右子树都不能偷
            v1 = root.val + left[1] + right[1]
            # 不偷当前节点, 则取左右子树中最大的值
            v2 = max(left) + max(right)
            return v1, v2

        return max(_rob(root))
相关推荐
千寻girling1 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook5 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风6 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风6 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei1 天前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
zone77391 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77391 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm
唐叔在学习2 天前
就算没有服务器,我照样能够同步数据
后端·python·程序员