Sum of Root To Leaf Binary Numbers — LeetCode 1022 Python Solution

EasyTreeDepth-First SearchBinary Tree
Problem
#1022
Reading time
3 min

The 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.

Example

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

Python solution

Python
# 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(root, t):
            if root is None:
                return 0
            t = (t << 1) | root.val
            if root.left is None and root.right is None:
                return t
            return dfs(root.left, t) + dfs(root.right, t)

        return dfs(root, 0)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1022. Sum of Root To Leaf Binary Numbers is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1022. Sum of Root To Leaf Binary Numbers?
LeetCode 1022. Sum of Root To Leaf Binary Numbers is rated Easy on LeetCode.
What is the time complexity of LeetCode 1022. Sum of Root To Leaf Binary Numbers?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1022. Sum of Root To Leaf Binary Numbers?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1022. Sum of Root To Leaf Binary Numbers cover?
LeetCode 1022. Sum of Root To Leaf Binary Numbers is tagged Tree, Depth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview