#129
Medium Algorithms Sum root to leaf numbers
Tree Depth-First Search Binary Tree
69.6% acceptance
Feb 27, 2026
8633
158
You are given the root of a binary tree containing digits from 0 to 9 only.
Each root-to-leaf path in the tree represents a number.
For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.
Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.
A leaf node is a node with no children.
Solution
Rust
Time O(n)
Space O(n)
// 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 sum_numbers(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
Self::sum_dfs(&root, 0)
}
fn sum_dfs(node: &Option<Rc<RefCell<TreeNode>>>, current: i32) -> i32 {
if let Some(n) = node {
let n = n.borrow();
let val = current * 10 + n.val;
if n.left.is_none() && n.right.is_none() {
return val;
}
Self::sum_dfs(&n.left, val) + Self::sum_dfs(&n.right, val)
} else {
0
}
}
}