The thief has found himself a new place for his thievery again. There is a entrance to this area, called the "root." Besides the root, each house have one and only one parent house. After a tour, the Smart thief realized the ' all houses in this ' place forms a binary tree. It would automatically contact the police if and 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 */Ten Public classSolution { One Public intRob (TreeNode root) { A int[] res =Robdfs (root); - returnMath.max (res[0],res[1]); - } the - Public int[] Robdfs (TreeNode root) { - if(Root = =NULL)return New int[2]; - int[] left =Robdfs (root.left); + int[] right =Robdfs (root.right); - int[] ans =New int[2]; +Ans[0] = left[1] + root.val + right[1]; AANS[1] = Math.max (left[0], left[1]) + Math.max (right[0],right[1]); at returnans; - } -}
In Dfs, when Root is null, an empty array of length 2 is returned;
When the resulting array res is established, Res[0] is the case that includes the root node, and res[1] is not the root node. Instead of dividing it by the left and right sub-trees.
337 House Robber III Java Solutions