337. House Robber III

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:

     3
    / \
   2   3
    \   \ 
     3   1

Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

 

Example 2:

     3
    / \
   4   5
  / \   \ 
 1   3   1

Maximum amount of money the thief can rob = 4 + 5 = 9.

题目含义:不能连续抢直接相连的两个节点。即例2中,抢了3就不能抢4,5。问最多能抢好多。

思路:给一个二叉树,求它不直接相连的节点的val和最大为多少。

如果抢了当前节点,那么它的左右孩子就肯定不能抢了。 
如果没有抢当前节点,左右孩子抢不抢取决于左右孩子的孩子的val大小。

复制代码
 1     private int[] dfs(TreeNode root)
 2     {
 3         int[] result = {0,0}; //result[0]表示抢当前节点 result[1]表示不抢当前节点
 4         if (root == null) return result;
 5         int[] leftResult = dfs(root.left);
 6         int[] rightResult = dfs(root.right);
 7         result[0] = leftResult[1] +rightResult[1] + root.val;//抢了当前节点,它的左右孩子就不可以抢了
 8         result[1] = Math.max(leftResult[0],leftResult[1]) + Math.max(rightResult[0],rightResult[1]);//不抢当前节点,左右孩子可抢可不抢
 9         return result;
10     }
11     
12     public int rob(TreeNode root) {
13         int[] result = dfs(root);
14         return Math.max(result[0],result[1]);        
15     }
复制代码

 

posted @   daniel456  阅读(120)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示