步骤一、确定递归函数的参数和返回值:
dp数组及下标的含义
dp数组的长度为2, 下标为0记录不偷该节点所得到的的最大金钱,下标为1记 录偷该节点所得到的的最大金钱。
步骤二、确定终止条件:
在遍历的过程中, 如果遇到空节点,很明显,无论偷还是不偷, 都是0 if not root: return [0, 0]
而这一步,就算dp的初始化
步骤三、确定遍历顺序:
对于树的遍历,一定要使用后序遍历,要通过递归函数的返回值来做下 一步的计算
先递归左节点, 得到左节点偷与不偷的金钱 left = robTree(root.left)
再递归右节点, 得到右节点偷与不偷的金钱 right = robTree(root.right)
步骤四、确定单层的递归逻辑(动态转移方程):
这个要分为当前节点偷或者不偷分别来讨论
如果偷当前节点, 那么左右孩子就不能偷, val1 = root.val + left[0] + right[0], 下标为0记录不偷左右孩子的最大金钱
如果不偷当前节点,那么左右孩子可以考虑偷了, 但偷不偷呢, 选最大的那个 val2 = max(left)+max(right)
所以最后当前节点的状态就是 [val2, val1],所以到根节点的时候,返回 这俩最大的即可。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rob(self, root: TreeNode) -> int:
if not root:
return 0
def robTree(root):
if not root: # 递归终止
return 0, 0
# 遍历
leftchild_steal, leftchild_nosteal = robTree(root.left)
rightchild_steal, rightchild_nosteal = robTree(root.right)
# 如果偷当前节点则左右孩子不能偷
steal = root.val + leftchild_nosteal + rightchild_nosteal
# 如果不偷当前节点,那么左右孩子可以考虑偷la
nosteal = max(leftchild_steal, leftchild_nosteal) + max(rightchild_steal, rightchild_nosteal)
return steal, nosteal
return max(robTree(root))