1. 程式人生 > >LeetCode-House Robber III

LeetCode-House Robber III

一、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;
    }
}