๐ 337. ๆๅฎถๅซ่ III
2022ๅนด6ๆ9ๆฅๅฐไบ 1 ๅ้
๐ 337. ๆๅฎถๅซ่ III
้พๅบฆ: ๐
้ฎ้ขๆ่ฟฐ
่งฃๆณ
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int rob(TreeNode root) {
// ๆ่ทฏ๏ผ
// ไบๅๆ ็ๅๅบ้ๅ + dp
int[] res = mySol(root);
return Math.max(res[0], res[1]);
}
private int[] mySol(TreeNode root) {
int[] res = new int[] {0, 0};
// ้ๅฝ็ปๆญขๆกไปถ
if(root == null) {
return res;
}
int[] left = mySol(root.left);
int[] right = mySol(root.right);
// ๅๅฑ้ๅฝ้ป่พ
res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
res[1] = left[0] + right[0] + root.val;
return res;
}
}