Leetcode 337.打家劫舍3(717)

题目

26年7月17日(首刷看解)

Go 复制代码
func rob(root *TreeNode) int {
   steal,notsteal:=dfs(root)
   return max(steal,notsteal)
}
func dfs(root *TreeNode)(int ,int){
    if root==nil{
        return 0,0
    }
    leftsteal,leftnotsteal:=dfs(root.Left)
    rightsteal,rightnotsteal:=dfs(root.Right)
    cursteal:=root.Val+leftnotsteal+rightnotsteal
    curnotsteal:=max(leftsteal,leftnotsteal)+max(rightsteal,rightnotsteal)
    return cursteal,curnotsteal
}

思路

这道题我一开始想到的就是之前做过那道安摄像头的题,想到用flag标记隔层,

大概就是这样 (错误的)

Go 复制代码
func rob(root *TreeNode) int {
    res1:=dfs(root,0,0)
    res2:=dfs(root,1,0)
    return max(res1,res2)
}
func dfs(root *TreeNode,flag int,total int) int{
    if root==nil{
        return 0
    }
    if flag==1{
        total+=root.Val
        total+=dfs(root.Left,0,total)
        total+=dfs(root.Right,0,total)
    }else{
        total+=dfs(root.Left,1,total)
        total+=dfs(root.Right,1,total)
    }
    return total
}

其实怎么说呢,我这里问题主要有total值作为参数传串了,左子树和右子树应该是独立的计算不能干扰 ,然后错误的点就是如果父节点没偷,相当于子节点就必偷了,其实也有父节点没偷,子节点也不偷才是金额最大的情况。比如3-1-2-3,模拟四层,偷第一层和最后一层才是最多的。

所以前序遍历就是错的,后序遍历才是对的,其实如果父亲没偷,就是找子节点偷和不偷的最大值,如果父亲偷了,就是找子节点没偷的最大值,是建立在先知道子节点的最大收益上的,所以选择后序遍历,

第一个就是遍历顺序 ,第二个就是返回值

这道题还有一个关键就是想到有两个返回值,分别代表偷和没偷,我几乎没遇到过这种情况,原来可以两个返回值,

然后剩下的就是把递归的三部+结合后序遍历模版,写代码了

相关推荐
怕浪猫8 小时前
RAG 面试 6 连问,从原理到优化全部覆盖
python·算法·面试
无线通信科研笔记8 小时前
IEEE TVT 2026 论文精读与完整复现|相位误差如何重塑近场 RIS 的幅相响应
论文阅读·人工智能·python·算法·论文笔记
To_OC9 小时前
从一头雾水到跑通全流程:我用一个周末啃透了JWT登录鉴权
前端·后端·http
mmmmath_39 小时前
二叉树の递归遍历
算法
All for pursuit.9 小时前
【位运算-1】338.比特位计数
数据结构·c++·算法·leetcode
前端兰博10 小时前
05-Redis
redis·后端
小师兄吃牛肉10 小时前
C语言中的nullptr有必要吗
c语言·c++·算法
databook10 小时前
从手动检查到自动监控:一个数据质量工作流的实现
后端·python·数据分析
【JAVA】玩家11 小时前
Spring核心原理全解析:从零到生产实战
java·后端·spring
东风破_11 小时前
从 Neo4j 到 GraphRAG:用 Text-to-Cypher 构建图检索 RAG
人工智能·后端