337. House Robber III

# Medium

Two methods:

  1. Recursive, from top to bottom to compute. Time consuming.

  2. DP, very node records the largest money from this node to leaf.

Solution 1:

Time complexity: h!h! , h is tree's height. Space complexity: O(1)O(1) .

Solution 2:

Time complexity: O(n)O(n) , n is number of nodes. Space complexity: O(h)O(h) , 这里的空间复杂度是栈道深度。

只存计算当前root->leaf最大的money. 则只需要知道其子节点(left&right)含节点和不含节点的最大值。⚠️含节点的最大值是max(含节点,不含节点),而不是必须包含次节点的最大值。由于每个节点需要知道两个值,所以用DP时要返回一对值。

Last updated

Was this helpful?