一、Description
题目描述:从根节点出发,返回一个最大的结点和,要求结点不能相邻。
Example 1:
Input: [3,2,3,null,3,null,1]
3
/ \
2 3
\ \
3 1
Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
Input: [3,4,5,1,3,null,1]
3
/ \
4 5
/ \ \
1 3 1
Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
二、Analyzation
对于一个结点root,只有两种策略——加或者不加,设left和right用来存放root的左子树和右子树的最大不相邻结点和,用subleft和subright存放与root不相邻的最大不相邻结点和,最后比较left + right和subleft + subright + root.val,返回最大值即可。
三、Accepted code
class Solution {
public int rob(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return root.val;
}
int left = 0, right = 0, subleft = 0, subright = 0;
if (root.left != null) {
left = rob(root.left);
subleft = rob(root.left.left) + rob(root.left.right);
}
if (root.right != null) {
right = rob(root.right);
subright = rob(root.right.left) + rob(root.right.right);
}
int sum1 = left + right;
int sum2 = subleft + subright + root.val;
return sum1 > sum2 ? sum1 : sum2;
}
}