The original title link is here: https://leetcode.com/problems/house-robber-iii/
Topic:
The thief has found himself a new place for his thievery again. There is a entrance to this area, called the "root." Besides the root, each house have one and only one parent house. After a tour, the Smart thief realized the ' all houses in this ' place forms a binary tree. It would automatically contact the police if and 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 1:
3 / 2 3 \ \ 3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3 / 4 5 /\ \ 1 3 1
Maximum amount of money the thief can rob = 4 + 5 = 9.
Exercises
Robroot = notrobleft + notrobright + root.val
Notrobroot = Math.max (Robleft, Notrobleft) + Math.max (Robright, Notrobright).
Dfs from the tree is updated from the bottom up.
Time Complexity:o (n). Space:o (LOGN). The LOGN layer stack is used.
AC Java:
1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One Public intRob (TreeNode root) { A int[] res =Dfs (root); - returnMath.max (Res[0], res[1]); - } the Private int[] DFS (TreeNode root) { - int[] DP =New int[2]; - if(Root = =NULL){ - returnDP; + } - int[] left =DFS (root.left); + int[] right =DFS (root.right); A //dp[0] means stealing root, then can't steal around, so use left[1], right[1]. atDp[0] = left[1] + right[1] +Root.val; - //dp[1] means not to steal root, then the right or left to steal can, take the maximum value -DP[1] = Math.max (left[0], left[1]) + Math.max (right[0], right[1]); - returnDP; - } -}
Similar to house robber, house robber Ii.
Leetcode House Robber III