sweet1cris

Untitled

Feb 9th, 2018
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.02 KB | None | 0 0
  1.  
  2. /**
  3.  * Definition for a binary tree node.
  4.  * public class TreeNode {
  5.  *     int val;
  6.  *     TreeNode left;
  7.  *     TreeNode right;
  8.  *     TreeNode(int x) { val = x; }
  9.  * }
  10.  */
  11. //dp[i][0]表示以i为根的子树不偷根节点能获得的最高价值,dp[i][1]表示以i为根的子树偷根节点能获得的最高价值
  12. public class Solution {
  13.     public int houseRobber3(TreeNode root) {
  14.         int[] ans = dp(root);
  15.         return Math.max(ans[0], ans[1]);
  16.     }
  17.     public int[] dp(TreeNode root) {
  18.         if (root == null) {
  19.             int[] now = new int[]{0, 0};
  20.             return now;
  21.         }
  22.         int[] left = dp(root.left);
  23.         int[] right = dp(root.right);
  24.         int[] now = new int[2];
  25.         now[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
  26.         now[1] = left[0] + right[0] + root.val;
  27.         return now;
  28.     }
  29. }
  30.  
  31. // version 2
  32. /**
  33.  * Definition of TreeNode:
  34.  * public class TreeNode {
  35.  *     public int val;
  36.  *     public TreeNode left, right;
  37.  *     public TreeNode(int x) { val = x; }
  38.  * }
  39.  */
  40. class ResultType {
  41.     public int rob, not_rob;
  42.     public ResultType() { rob = not_rob = 0; }
  43. }
  44.  
  45. public class Solution {
  46.     /**
  47.      * @param root: The root of binary tree.
  48.      * @return: The maximum amount of money you can rob tonight
  49.      */
  50.     public int houseRobber3(TreeNode root) {
  51.         // write your code here
  52.         ResultType result = visit(root);
  53.         return Math.max(result.rob, result.not_rob);
  54.     }
  55.    
  56.     public ResultType visit(TreeNode root) {
  57.         ResultType result = new ResultType();
  58.         if (root == null)
  59.             return result;
  60.            
  61.         ResultType left_result = visit(root.left);
  62.         ResultType right_result = visit(root.right);
  63.        
  64.         result.rob = root.val + left_result.not_rob + right_result.not_rob;
  65.         result.not_rob = Math.max(left_result.rob, left_result.not_rob) +
  66.                          Math.max(right_result.rob, right_result.not_rob);
  67.         return result;
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment