1988coder

337. House Robber III

Jan 1st, 2019
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.92 KB | None | 0 0
  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. /**
  11.  * Recursive Greedy Solution.
  12.  *
  13.  * Time Complexity: O(N)
  14.  *
  15.  * Space Complexity: O(N)
  16.  *
  17.  * N = Number of nodes in the tree.
  18.  */
  19. class Solution {
  20.     public int rob(TreeNode root) {
  21.         if (root == null) {
  22.             return 0;
  23.         }
  24.         int[] result = robHelper(root);
  25.         return Math.max(result[0], result[1]);
  26.     }
  27.  
  28.     private int[] robHelper(TreeNode node) {
  29.         if (node == null) {
  30.             return new int[2];
  31.         }
  32.  
  33.         int[] left = robHelper(node.left);
  34.         int[] right = robHelper(node.right);
  35.  
  36.         int[] res = new int[2];
  37.         res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
  38.         res[1] = node.val + left[0] + right[0];
  39.  
  40.         return res;
  41.     }
  42. }
Add Comment
Please, Sign In to add comment