#366
Medium Algorithms Find leaves of binary tree
Tree Depth-First Search Binary Tree
81.3% acceptance
Mar 31, 2026
3304
64
No description available.
Solution
Rust
Time O(n)
Space O(n)
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn find_leaves(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
let mut result = Vec::new();
fn height(node: &Option<Rc<RefCell<TreeNode>>>, result: &mut Vec<Vec<i32>>) -> i32 {
match node {
None => -1,
Some(n) => {
let n = n.borrow();
let h = 1 + height(&n.left, result).max(height(&n.right, result));
if h as usize >= result.len() {
result.resize(h as usize + 1, Vec::new());
}
result[h as usize].push(n.val);
h
}
}
}
height(&root, &mut result);
result
}
}