淘先锋技术网

首页 1 2 3 4 5 6 7

Problem

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example

  3
 / \
2   3
 \   \ 
  3   1

Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

    3
   / \
  4   5
 / \   \ 
1   3   1

Maximum amount of money the thief can rob = 4 + 5 = 9.

Note

DFS解法真的非常巧妙,不过这道题里仍要注意两个细节。
DFS中,root为null时,返回长度为2的空数组;
建立结果数组A时,A[0]是包括根节点的情况,A[1]是不包含根节点的情况。而非按左右子树来进行划分的。

Solution

public class Solution {
    public int houseRobber3(TreeNode root) {
        int[] A = dfs(root);
        return Math.max(A[0], A[1]);
    }
    public int[] dfs(TreeNode root) {
        if (root == null) return new int[2];
        int[] left = dfs(root.left);
        int[] right = dfs(root.right);
        int[] A = new int[2];
        A[0] = left[1] + root.val + right[1];
        A[1] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
        return A;
    }
}