Forgetting null/base-case handling
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.
Build confidence with an intuition-first walkthrough focused on tree fundamentals.
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.
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.
Example 1:
Input: root = [1,0,1,0,1,0,1] Output: 22 Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
Example 2:
Input: root = [0] Output: 0
Constraints:
[1, 1000].Node.val is 0 or 1.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Tree
[1,0,1,0,1,0,1]
[0]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1022: Sum of Root To Leaf Binary Numbers
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int sumRootToLeaf(TreeNode root) {
return dfs(root, 0);
}
private int dfs(TreeNode root, int x) {
if (root == null) {
return 0;
}
x = x << 1 | root.val;
if (root.left == root.right) {
return x;
}
return dfs(root.left, x) + dfs(root.right, x);
}
}
// Accepted solution for LeetCode #1022: Sum of Root To Leaf Binary Numbers
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sumRootToLeaf(root *TreeNode) int {
var dfs func(*TreeNode, int) int
dfs = func(root *TreeNode, x int) int {
if root == nil {
return 0
}
x = x<<1 | root.Val
if root.Left == root.Right {
return x
}
return dfs(root.Left, x) + dfs(root.Right, x)
}
return dfs(root, 0)
}
# Accepted solution for LeetCode #1022: Sum of Root To Leaf Binary Numbers
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
def dfs(root: Optional[TreeNode], x: int) -> int:
if root is None:
return 0
x = x << 1 | root.val
if root.left == root.right:
return x
return dfs(root.left, x) + dfs(root.right, x)
return dfs(root, 0)
// Accepted solution for LeetCode #1022: Sum of Root To Leaf Binary Numbers
// 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>>>, x: i32) -> i32 {
if let Some(n) = node {
let n_ref = n.borrow();
let x = (x << 1) | n_ref.val;
if n_ref.left.is_none() && n_ref.right.is_none() {
return x;
}
dfs(n_ref.left.clone(), x) + dfs(n_ref.right.clone(), x)
} else {
0
}
}
dfs(root, 0)
}
}
// Accepted solution for LeetCode #1022: Sum of Root To Leaf Binary Numbers
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function sumRootToLeaf(root: TreeNode | null): number {
const dfs = (node: TreeNode | null, x: number): number => {
if (node === null) {
return 0;
}
x = (x << 1) | node.val;
if (node.left === null && node.right === null) {
return x;
}
return dfs(node.left, x) + dfs(node.right, x);
};
return dfs(root, 0);
}
Use this to step through a reusable interview workflow for this problem.
BFS with a queue visits every node exactly once — O(n) time. The queue may hold an entire level of the tree, which for a complete binary tree is up to n/2 nodes = O(n) space. This is optimal in time but costly in space for wide trees.
Every node is visited exactly once, giving O(n) time. Space depends on tree shape: O(h) for recursive DFS (stack depth = height h), or O(w) for BFS (queue width = widest level). For balanced trees h = log n; for skewed trees h = n.
Review these before coding to avoid predictable interview regressions.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.