Skip to main content
Back to problems
#337
Medium Algorithms

House robber iii

Dynamic Programming Tree Depth-First Search Binary Tree
55.6% acceptance
Feb 27, 2026
9077
157
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root. Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night. Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
// 
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
  pub fn rob(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
    fn dfs(node: &Option<Rc<RefCell<TreeNode>>>) -> (i32, i32) {
      if let Some(n) = node {
        let n = n.borrow();
        let (left_rob, left_not_rob) = dfs(&n.left);
        let (right_rob, right_not_rob) = dfs(&n.right);
        
        let rob = n.val + left_not_rob + right_not_rob;
        let not_rob = left_rob.max(left_not_rob) + right_rob.max(right_not_rob);
        
        (rob, not_rob)
      } else {
        (0, 0)
      }
    }
    
    let (rob, not_rob) = dfs(&root);
    rob.max(not_rob)
  }
}