LeetCode House Robber III

来源:互联网 发布:java与php哪个好 编辑:程序博客网 时间:2024/06/05 13:31

Description:

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.


Solution:

DFS+DP


/** * Definition for a binary tree node. public class TreeNode { int val; TreeNode * left; TreeNode right; TreeNode(int x) { val = x; } } */public class Solution {public int[] dfs(TreeNode node) {int rob[] = { 0, 0 };if (node == null)return rob;int[] left = dfs(node.left);int[] right = dfs(node.right);rob[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);rob[1] = node.val + left[0] + right[0];return rob;}public int rob(TreeNode root) {if (root == null)return 0;int[] ans = dfs(root);return Math.max(ans[0], ans[1]);}}


0 0
原创粉丝点击