Problem

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.

Examples

Example 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10

![](https://assets.leetcode.com/uploads/2019/04/04/sum-of-root-to-leaf-binary-
numbers.png)

    
    
    Input: root = [1,0,1,0,1,0,1]
    Output: 22
    Explanation:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
    

Example 2

1
2
3
4
5
6

    
    
    Input: root = [0]
    Output: 0
    

Constraints

  • The number of nodes in the tree is in the range [1, 1000].
  • Node.val is 0 or 1.

Solution

Approach

We use DFS to traverse the tree, keeping track of the current path as a binary number. When we reach a leaf, we add the current value to the result. This can be done recursively.


Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
    int sumRootToLeaf(TreeNode* root, int val = 0) {
        if (!root) return 0;
        val = (val << 1) | root->val;
        if (!root->left && !root->right) return val;
        return sumRootToLeaf(root->left, val) + sumRootToLeaf(root->right, val);
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int x) { val = x; }
}
class Solution {
    public int sumRootToLeaf(TreeNode root) {
        return dfs(root, 0);
    }
    private int dfs(TreeNode node, int val) {
        if (node == null) return 0;
        val = (val << 1) | node.val;
        if (node.left == null && node.right == null) return val;
        return dfs(node.left, val) + dfs(node.right, val);
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class TreeNode(var `val`: Int) {
    var left: TreeNode? = null
    var right: TreeNode? = null
}
class Solution {
    fun sumRootToLeaf(root: TreeNode?): Int {
        fun dfs(node: TreeNode?, v: Int): Int {
            if (node == null) return 0
            val nv = (v shl 1) or node.`val`
            if (node.left == null && node.right == null) return nv
            return dfs(node.left, nv) + dfs(node.right, nv)
        }
        return dfs(root, 0)
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# 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: TreeNode) -> int:
        def dfs(node, val):
            if not node:
                return 0
            val = (val << 1) | node.val
            if not node.left and not node.right:
                return val
            return dfs(node.left, val) + dfs(node.right, val)
        return dfs(root, 0)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Definition for a binary tree node.
// struct TreeNode {
//     pub val: i32,
//     pub left: Option<Rc<RefCell<TreeNode>>>,
//     pub right: Option<Rc<RefCell<TreeNode>>>,
// }
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>>>, val: i32) -> i32 {
            if let Some(n) = node {
                let n = n.borrow();
                let nv = (val << 1) | n.val;
                if n.left.is_none() && n.right.is_none() {
                    return nv;
                }
                dfs(n.left.clone(), nv) + dfs(n.right.clone(), nv)
            } else { 0 }
        }
        dfs(root, 0)
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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 {
    function dfs(node: TreeNode | null, val: number): number {
        if (!node) return 0
        val = (val << 1) | node.val
        if (!node.left && !node.right) return val
        return dfs(node.left, val) + dfs(node.right, val)
    }
    return dfs(root, 0)
}

Complexity

  • ⏰ Time complexity: O(n)
  • 🧺 Space complexity: O(h) where h is the height of the tree