标签:
题目:
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.
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 robMoney=0; 13 if(root==null) 14 { 15 return 0; 16 } 17 robMoney=robsub(root); 18 return robMoney; 19 } 20 public int robsub(TreeNode root) { 21 int rob=0; 22 if(root==null) 23 return 0; 24 else if(root.left==null&&root.right==null) 25 return root.val; 26 else { 27 int robroot=0; 28 int robother=robsub(root.left)+robsub(root.right); 29 if(root.left==null) 30 robroot=root.val+robsub(root.right.left)+robsub(root.right.right); 31 else if(root.right==null) 32 robroot=root.val+robsub(root.left.left)+robsub(root.left.right); 33 else 34 robroot=root.val+robsub(root.left.left)+robsub(root.left.right)+robsub(root.right.left)+robsub(root.right.right); 35 if(robroot>robother) 36 rob=robroot; 37 else 38 rob=robother; 39 } 40 return rob; 41 } 42 }
leetcode 337. House Robber III
标签:
原文地址:http://www.cnblogs.com/HelloWorld-5/p/5421247.html