337. House Robber III

問題描述

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.

思路

類似House Robber I,不過這里用recursive的方法,每個(gè)被延伸到的node都返回一個(gè)tuple, 類似由pre, cur = cur, max(cur, pre+nums[i])后的pre和cur
先判斷base case,如果不是root,返回(0, 0)
否則,一直向左右延伸;又因?yàn)槊看味加蟹祷刂?,所以用一個(gè)在延伸時(shí),用一個(gè)變量把值存起來,用于后面返回值的計(jì)算

class Solution:
    def rob(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        return self.test(root)[1]
        
    def test(self, root):
        if not root:
            return (0,0)
        if (root):
            l = self.test(root.left)
            r = self.test(root.right)
            return (l[1]+r[1], max(l[1]+r[1], l[0]+r[0]+root.val))
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容