Problem 1022

Abstract / Summary

Given a binary tree where each node has a 0 or 1 value, find the total of all numbers formed from root to leaf paths.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1022.py

class Solution:
    def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
        leafs = []
        def deeper(node, have):
            if node:
                have <<= 1
                have  += node.val
                if node.left or node.right:
                    deeper(node.left,  have)
                    deeper(node.right, have)
                else:
                    leafs.append(have)

        deeper(root, 0)
        return sum(leafs)
15 lines | 472 bytes | submitted December 13, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (200k+ submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Depth First Search
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single public method sumRootToLeaf. The method receives the root of a binary tree whose nodes contain binary digits (0 or 1) and returns the sum of the integer values represented by all root-to-leaf paths. Each path is interpreted as a binary number where the most significant bit is at the root. The algorithm traverses the tree depth-first, builds the numeric value incrementally, stores the completed values for leaf nodes, and finally aggregates them with Python’s built-in sum.

Key Steps

The core of the solution is the nested helper function deeper. It receives a node reference and an accumulator have that holds the binary value constructed so far.

def deeper(node, have):
    if node:
        have <<= 1
        have  += node.val
        if node.left or node.right:
            deeper(node.left,  have)
            deeper(node.right, have)
        else:
            leafs.append(have)
  1. Node existence check - The guard if node: ensures that the recursion stops when a null child is encountered, preventing attempts to access attributes on a None object.

  2. Binary accumulation - The line have <<= 1 left-shifts the current value, effectively multiplying it by two, and have += node.val adds the current node’s bit. This mirrors the process of appending a new binary digit to the right side of a number.

  3. Branching decision - The condition if node.left or node.right: distinguishes internal nodes from leaves. When at least one child exists, the function recurses on both left and right subtrees, passing the updated accumulator.

  4. Leaf handling - When a node has no children, the accumulated binary value represents a complete root-to-leaf number. It is appended to the list leafs for later summation.

After the recursive traversal completes, the method returns the total of all collected leaf values:

deeper(root, 0)
return sum(leafs)

The initial call starts with an accumulator of zero, representing an empty binary prefix.

Edge Cases Handled

The implementation gracefully manages several edge conditions without explicit branching outside the main recursion:

  • Empty tree - If root is None, the initial call to deeper immediately fails the if node: guard, leaving leafs empty. The final sum(leafs) therefore returns 0, correctly representing the sum of an absent set of paths.

  • Single-node tree - When the tree consists of only the root, the node has neither left nor right child. The recursion treats this node as a leaf, computes have as node.val, appends it to leafs, and the sum returns that single value.

  • Unbalanced trees - The depth-first recursion does not rely on any balance property. Whether the tree leans heavily to one side or contains long chains, each node is visited exactly once, and leaf detection (node.left or node.right) works uniformly.

  • Nodes with value zero - The binary accumulation correctly incorporates zero bits. The left-shift operation preserves the existing bits, and adding 0 leaves the accumulator unchanged for that position, ensuring that leading zeros in a path do not affect the numeric result.

Performance Optimizations

The code exhibits several implicit optimizations that contribute to efficient execution:

  • In-place accumulation - By updating have through bitwise left-shift and addition, the algorithm avoids constructing intermediate strings or lists to represent the binary path. This keeps memory usage low and leverages fast integer arithmetic.

  • Tail-recursive style for leaf capture - The leaf values are stored only when a leaf is reached, eliminating the need to keep partial results for internal nodes. The list leafs therefore contains at most one entry per leaf, minimizing storage overhead.

  • Single traversal - The depth-first search visits each node exactly once, performing a constant amount of work per node (a shift, an addition, and a couple of attribute checks). This linear visitation pattern ensures that the total work scales directly with the number of nodes.

  • Built-in aggregation - Using Python’s native sum function to combine the leaf values leverages a highly optimized C implementation, which is faster than a manual accumulation loop written in pure Python.

Overall, the solution combines a concise recursive structure with integer-centric operations, delivering a clear and performant approach to summing binary numbers represented by root-to-leaf paths.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a tree made of branches that start at the top and spread out toward the ground. Each branch has a little number attached to it. The goal is to walk from the very top piece all the way down to the bottom tips, picking up numbers along the way to build a secret code.

The code starts at the top piece. It keeps track of the numbers gathered so far by sliding them over to make room for a new digit and then adding the new piece. Think of this like shifting blocks to make a longer train.

Every time the path hits a split, the code decides to explore both directions to see where they lead. If a branch keeps going, the code keeps walking and collecting numbers. When a branch reaches a tip where there is nothing else to follow, the code knows the secret path is finished. It puts that finished path into a list, almost like saving a completed puzzle piece in a box.

Once every single path from the top to the bottom tips has been walked, the code looks at all the finished pieces inside the box and puts them together to find the final total.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.44 | σ = 1.64

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fpdjsns C++
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
withaarzoo C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fpdjsns C++
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
withaarzoo C++
YuriSpiridonov Python
38 links | 24 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   December 13, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality