/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ public class Solution { public int Rob(TreeNode root) { int[] num = dfs(root); return Math.Max(num[0], num[1]); } private int[] dfs(TreeNode x) { if (x == null) return new int[2]; int[] left = dfs(x.left); int[] right = dfs(x.right); int[] res = new int[2]; res[0] = left[1] + right[1] + x.val; res[1] = Math.Max(left[0], left[1]) + Math.Max(right[0], right[1]); return res; } }
https://leetcode.com/problems/house-robber-iii/#/description
补充一个python的实现:
1 class Solution: 2 def dfs(self,root): 3 if root==None: 4 return [0,0]#空节点 5 counter = [0,0] 6 left = self.dfs(root.left) 7 right = self.dfs(root.right) 8 9 #取当前节点,则其左右子节点都不能取 10 counter[0] = root.val + left[1] + right[1] 11 12 #不取当前节点,则左右子节点是否选取要看子节点选择是否更大 13 counter[1] = max(left[0],left[1]) + max(right[0],right[1]) 14 return counter 15 16 def rob(self, root: 'TreeNode') -> 'int': 17 result = self.dfs(root) 18 #第一位表示取当前节点的累计值,第二位表示不取当前节点的累计值 19 return max(result[0],result[1])