Skip to main content
Back to problems
#1469
Easy Algorithms

Find all the lonely nodes

Tree Depth-First Search Breadth-First Search Binary Tree
84.1% acceptance
Mar 31, 2026
519
11

No description available.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
use std::rc::Rc;
use std::cell::RefCell;

impl Solution {
  pub fn get_lonely_nodes(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
    let mut result = Vec::new();
    fn dfs(node: &Option<Rc<RefCell<TreeNode>>>, result: &mut Vec<i32>) {
      if let Some(n) = node {
        let n = n.borrow();
        let has_left = n.left.is_some();
        let has_right = n.right.is_some();
        if has_left && !has_right {
          result.push(n.left.as_ref().unwrap().borrow().val);
        } else if !has_left && has_right {
          result.push(n.right.as_ref().unwrap().borrow().val);
        }
        dfs(&n.left, result);
        dfs(&n.right, result);
      }
    }
    dfs(&root, &mut result);
    result
  }
}