#1022
Easy Algorithms Sum of root to leaf binary numbers
Tree Depth-First Search Binary Tree
76.6% acceptance
Feb 27, 2026
3774
212
You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit.
For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers.
The test cases are generated so that the answer fits in a 32-bits integer.
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_root_to_leaf(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
fn dfs(node: &Option<Rc<RefCell<TreeNode>>>, cur: i32) -> i32 {
if let Some(n) = node {
let val = cur * 2 + n.borrow().val;
let l = n.borrow().left.clone();
let r = n.borrow().right.clone();
if l.is_none() && r.is_none() { return val; }
dfs(&l, val) + dfs(&r, val)
} else { 0 }
}
dfs(&root, 0)
}
}