Graph Theory37 sections · 1633 units
Open in Course

LeetCode 337 House Robber III - Walkthrough

Example tree trace

Tree: root 33, left 22 (left 33), right 33 (right 11). DFS leaf 33 (left of 22): returns (0,3)(0, 3). DFS node 22: exclude =3= 3, include =2= 2. Returns (3,2)(3, 2). DFS leaf 11 (right of 33): returns (0,1)(0, 1). DFS node 33 (right): exclude =1= 1, include =3= 3.

Returns (1,3)(1, 3). DFS root: exclude =max(3,2)+max(1,3)=6= max(3, 2) + max(1, 3) = 6, include =3+3+1=7= 3 + 3 + 1 = 7. Answer: 77. Taking the root and both grandchildren gives the maximum.