Skip to main content
Back to problems
#1325
Medium Algorithms

Delete leaves with a given value

Tree Depth-First Search Binary Tree
77.3% acceptance
Feb 27, 2026
2892
59
Given a binary tree root and an integer target, delete all the leaf nodes with value target. Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot).

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
  pub fn remove_leaf_nodes(
    root: Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>,
    target: i32,
  ) -> Option<std::rc::Rc<std::cell::RefCell<TreeNode>>> {
    if let Some(node) = root {
      let left = {
        let l = node.borrow().left.clone();
        Self::remove_leaf_nodes(l, target)
      };
      let right = {
        let r = node.borrow().right.clone();
        Self::remove_leaf_nodes(r, target)
      };
      node.borrow_mut().left = left;
      node.borrow_mut().right = right;
      let is_leaf = node.borrow().left.is_none() && node.borrow().right.is_none();
      if is_leaf && node.borrow().val == target {
        return None;
      }
      Some(node)
    } else {
      None
    }
  }
}