1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| object steal {
case class TreeNode(var value:Int, var left: TreeNode, var right:TreeNode)
def rob(root: TreeNode): Int = { var f = Map[TreeNode, Int]() var g = Map[TreeNode, Int]()
def dfs(node:TreeNode):Unit = { if (node == null) { return } dfs(node.left) dfs(node.right) val fl = f.getOrElse(node.left, 0) val fr = f.getOrElse(node.right, 0) val gl = g.getOrElse(node.left, 0) val gr = g.getOrElse(node.right, 0) f = f + (node -> (node.value + gl + gr)) g = g + (node -> (scala.math.max(fl, gl) + scala.math.max(fr, gr)))
} dfs(root) scala.math.max(f.getOrElse(root, 0), g.getOrElse(root, 0)) }
def main(args: Array[String]): Unit = { val tree = TreeNode(3, TreeNode(3, null, null), TreeNode(4, TreeNode(4, null, null), null))
println(rob(tree)) }
}
|