Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Recursion of course. But please make sure you cover all the cases.

class Solution(object):
    # return: max value with node picked, max val w\o node picked
    def calcNode(self, node):
        if node is None:
            return 0, 0
        
        il, el = self.calcNode(node.left)
        ir, er = self.calcNode(node.right)
        
        return node.val + el + er, max(il, el) + max(ir, er)

    def rob(self, root):
        ml, mr = self.calcNode(root)
        return max(ml, mr)
posted on 2016-03-12 14:09  Tonix  阅读(137)  评论(0编辑  收藏  举报