/house_robber_III.kt Secret
Created
October 17, 2021 14:17
leetcode 337
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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