Graph Theory37 sections · 1633 units
Open in Course

LeetCode 337 House Robber III - Implementation

DFS returning pair

Write a DFS function that returns a pair (extexclude,extinclude)( ext{exclude}, ext{include}) for each node. Pseudocode:

function dfs(v)
    if v is null then
        return (0, 0)
    (left0, left1) := dfs(v.left)
    (right0, right1) := dfs(v.right)
    rob := v.val + left0 + right0
    skip := max(left0, left1) + max(right0, right1)
    return (skip, rob)

Return max of both states at root. Time O(n)O(n), space O(h)O(h) where hh is tree height.