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.
This problem is essentially the same as the previous two questions. But the difference is that the problem is btree. The first best thing to think about is Norob and Rob two method, calculated separately. Specific code is as follows
Public intRob (TreeNode root) {returnMath.max (Robb (Root), Norob (root)); } Public intRobb (TreeNode root) {if(Root = =NULL)return 0; varleft =Norob (Root.left); varright =Norob (root.right); returnleft+right+Root.val; } Public intnorob (TreeNode root) {if(Root = =NULL)return 0; returnMath.max (Robb (Root.left), Norob (root.left)) +Math.max (Robb (root.right), Norob (Root.right)); }
This time the submit is timed out. The problem is that inside Robb and Norob two method actually repeat many times. The algorithm needs to be improved, one solution is to output is an array. The first number is the one that happens to rob, and the second number is the maximum value of the node that does not have Rob. Finally, just compare the root output of this even value, take the maximum value is good.
The specific code is
Public intRob (TreeNode root) {varres =Robb (root); returnMath.max (res[0],res[1]); } Public int[] Robb (TreeNode root) {varres =New int[2]; res[0] =0; res[1] =0; if(Root = =NULL)returnRes; varleft =Robb (Root.left); varright =Robb (root.right); res[0] = root.val+left[1]+right[1]; res[1] = Math.max (left[0],left[1]) + Math.max (right[0],right[1]); returnRes; }
Think of the first way to achieve this. Theoretically, it is possible to add a hashtable to each node's extremum at the time of input.
337. House Robber III