Skip to content

Commit 343efea

Browse files
Implement House Robber III for binary tree
1 parent 9d311db commit 343efea

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class HouseRobberIII {
17+
public int rob(TreeNode root) {
18+
int[] result = postorder(root);
19+
return Math.max(result[0], result[1]);
20+
}
21+
22+
int[] postorder(TreeNode node){
23+
if(node == null){
24+
return new int[]{0,0};
25+
}
26+
27+
int[] left = postorder(node.left);
28+
int[] right = postorder(node.right);
29+
30+
int robLeft = left[0];
31+
int skipLeft = left[1];
32+
33+
int robRight = right[0];
34+
int skipRight = right[1];
35+
36+
return new int[]{node.val+skipLeft+skipRight, Math.max(robLeft, skipLeft)+Math.max(robRight, skipRight)};
37+
}
38+
}

0 commit comments

Comments
 (0)