LeetCode Entry
1022. Sum of Root To Leaf Binary Numbers
Sum of a binary numbers in a binary tree
1022. Sum of Root To Leaf Binary Numbers easy blog post substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1279
Problem TLDR
Sum of a binary numbers in a binary tree #easy
Intuition
The simplest way: helper method, global sum variable, track leafs.
Approach
- we can skip checking the leafs
- we can use tree itself as a storage
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(log(n))\)
Code
// 18ms
fun sumRootToLeaf(r: TreeNode?): Int = r?.run {
max(`val`, setOf(left,right).sumOf { it?.`val` += `val`*2; sumRootToLeaf(it) })
} ?: 0
// 0ms
pub fn sum_root_to_leaf(r: Option<Rc<RefCell<TreeNode>>>) -> i32 {
r.map_or(0, |n| { let n = n.borrow_mut();
[&n.left, &n.right].into_iter().flatten().map(|x| {
x.borrow_mut().val += n.val * 2;
Self::sum_root_to_leaf(Some(x.clone()))}).sum::<i32>().max(n.val)
})
}