The thief has found himself a new place for his thievery again. There is only one entrance to this area, called 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 form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.
Example 1:
Input: root = [3,2,3,null,3,null,1]
Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
Input: root = [3,4,5,1,3,null,1]
Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
解答
方法一
Recursion
Runtime: 100 ms, faster than 54.72% of JavaScript online submissions for House Robber III.
Memory Usage: 47.5 MB, less than 20.47% of JavaScript online submissions for House Robber III.
方法二
類似方法一的 recursion (稍微簡化)
Runtime: 109 ms, faster than 41.15% of JavaScript online submissions for House Robber III.
Memory Usage: 47.8 MB, less than 14.62% of JavaScript online submissions for House Robber III.
方法三
利用 hashmap 紀錄拜訪過節點的最大值
Runtime: 139 ms, faster than 13.08% of JavaScript online submissions for House Robber III.
Memory Usage: 48.6 MB, less than 8.46% of JavaScript online submissions for House Robber III.