Skip to content

Instantly share code, notes, and snippets.

@griffinmichl
Created June 17, 2016 20:05
Show Gist options
  • Select an option

  • Save griffinmichl/fdb09cc0823b7486fc974a3ea5a67013 to your computer and use it in GitHub Desktop.

Select an option

Save griffinmichl/fdb09cc0823b7486fc974a3ea5a67013 to your computer and use it in GitHub Desktop.
function rob(root) {
const memo = new Map()
function rob_helper(node) {
if (node === null) return 0
if (memo.get(node)) {
return memo.get(node)
}
let keep = node.val
if (node.left) {
keep += rob_helper(node.left.left)
keep += rob_helper(node.left.right)
}
if (node.right) {
keep += rob_helper(node.right.left)
keep += rob_helper(node.right.right)
}
let dontKeep = rob_helper(node.left) + rob_helper(node.right)
const result = Math.max(keep, dontKeep)
memo.set(node, result)
return result
}
return rob_helper(root)
}
const node1 = {val: 3, left: null, right: null}
const node2 = {val: 4, left: null, right: null}
const node3 = {val: 5, left: null, right: null}
const node4 = {val: 1, left: null, right: null}
const node5 = {val: 15, left: null, right: null}
const node6 = {val: 1, left: null, right: null}
node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
node3.right = node6
console.log(rob(node1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment