Skip to content

Instantly share code, notes, and snippets.

@terracotta-ko
Created October 17, 2021 14:17
leetcode 337
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun rob(root: TreeNode?): Int {
val ans = dfs(root)
return Math.max(ans[0], ans[1])
}
fun dfs(node: TreeNode?): IntArray {
return if(node == null) {
IntArray(2) {0}
} else {
val left = dfs(node!!.left)
val right = dfs(node!!.right)
val result = IntArray(2)
//>> select root
result[0] = node!!.`val` + left[1] + right[1]
//>> select child
result[1] = Math.max(left[0], left[1]) + Math.max(right[0], right[1])
return result
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment