标签:
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.
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int rob(TreeNode root) { 12 int[] res = Robdfs(root); 13 return Math.max(res[0],res[1]); 14 } 15 16 public int[] Robdfs(TreeNode root){ 17 if(root == null) return new int[2]; 18 int[] left = Robdfs(root.left); 19 int[] right = Robdfs(root.right); 20 int[] ans = new int[2]; 21 ans[0] = left[1] + root.val + right[1]; 22 ans[1] = Math.max(left[0], left[1]) + Math.max(right[0],right[1]); 23 return ans; 24 } 25 }
DFS中,root为null时,返回长度为2的空数组;
建立结果数组res时,res[0]是包括根节点的情况,res[1]是不包含根节点的情况。而非按左右子树来进行划分的。
337. House Robber III java solutions
标签:
原文地址:http://www.cnblogs.com/guoguolan/p/5452979.html