Problem 653

Abstract / Summary

Given a binary search tree and a target number, determine if there exist two elements in the tree that add up to the target.

Note

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

Python 0653.py

class Solution:
    def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
        flat = set()
        def deeper(node):
            if not node:
                return False

            other = k - node.val
            if other in flat:
                return True

            flat.add(node.val)
            return deeper(node.left) or deeper(node.right)

        return deeper(root)
15 lines | 412 bytes | submitted October 3, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 64% (1+ million submissions).

Typical patterns to solve this problem:
  • Binary Search Tree
  • Binary Tree
  • Breadth First Search
  • Depth First Search
  • Hash Table
  • Tree
  • Two Pointers
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 determines whether a binary tree contains two distinct nodes whose values sum to a given target k. It performs a depth-first traversal while maintaining a hash-set of values seen so far. As each node is visited, the algorithm checks whether the complementary value required to reach k has already been encountered. If such a complement exists, the function returns true; otherwise it continues the search until all nodes have been examined.

Key Steps

The algorithm can be broken down into a few distinct operations, each illustrated with the corresponding fragment of source code.

Initialization of the lookup container

flat = set()

A hash-set named flat is created before the traversal begins. This container stores the values of nodes that have already been processed, enabling constant-time membership tests.

Definition of the recursive search routine

def deeper(node):
    if not node:
        return False
    ...

A nested function deeper is declared to encapsulate the depth-first search logic. The early return on a falsy node handles leaf-level termination.

Computation of the required complement

other = k - node.val

For the current node, the algorithm computes the value that would pair with node.val to achieve the target sum k. This value is stored in other.

Immediate detection of a matching pair

if other in flat:
    return True

The set flat is queried to see whether the complement other has already been observed. Because set lookups are constant-time, this check is highly efficient. If a match is found, the recursion short-circuits and propagates True upward.

Recording the current node’s value

flat.add(node.val)

When no complement is present, the current node’s value is added to flat. This ensures that subsequent nodes deeper in the tree can discover a pair involving this value.

Recursive descent into subtrees

return deeper(node.left) or deeper(node.right)

The function proceeds to explore the left child first; if the left subtree does not yield a solution, the right subtree is examined. The logical or guarantees that a True result from either side is returned immediately.

Invocation of the search from the entry point

return deeper(root)

The public method findTarget launches the recursive process by calling deeper with the root of the tree.

Edge Cases Handled

The implementation gracefully manages several boundary conditions without additional code.

When the input tree is empty (root is None), the initial call to deeper receives a falsy node, triggering the base case and returning False.

If the tree contains only a single node, the complement calculation will never find a matching entry in flat because the set is empty at that point, and the recursion will terminate after both child calls receive None.

Duplicate values are accommodated because each occurrence is added to the set only once; the algorithm still correctly identifies a pair if two distinct nodes share the same value that together satisfy the target sum.

Negative integers and large magnitude values pose no difficulty, as the arithmetic and set operations are agnostic to sign and size within Python’s integer range.

The early-return mechanism ensures that once a valid pair is discovered, no further traversal occurs, preventing unnecessary work on the remaining portions of the tree.

Performance Optimizations

The code leverages a hash-set to achieve constant-time checks for the required complement, eliminating the need for nested loops or repeated scans of previously visited nodes.

Depth-first recursion provides a natural stack-based traversal that visits each node at most once, and the use of the logical or operator allows the function to stop exploring as soon as a solution is found, avoiding the overhead of traversing the entire structure when it is not required.

By adding each node’s value to the set only after the complement test, the algorithm ensures that a node is never paired with itself, preserving correctness while keeping the set size minimal-only values from the path already examined are stored.

Overall, the combination of early exit, constant-time lookups, and a single pass through the tree constitutes an efficient solution for the two-sum problem on binary trees.

written by openai gpt

ELI5 - Simplified Explanation

Imagine the computer is walking through a giant family tree made of numbers. Each person in the tree is holding a special number. The goal is to see if any two people are holding numbers that add up to a specific target number.

To do this, the computer carries a magic empty bucket. It starts at the very top of the tree and looks at the number the first person is holding. It asks if there is a number inside the bucket that would combine with this one to make the target. If the bucket is empty or the math does not work, the computer carefully puts the current number into the bucket so it can remember it for later.

Then, the computer moves to the next person hanging down on the left side or the right side. It repeats the same steps again and again. Every time it visits a new person, it checks the bucket to see if it can find a partner number that matches perfectly. If it finds two numbers that add up to the goal, the puzzle is solved. If it reaches the bottom of the tree and finds nothing, then those two pieces are not hiding in the family.

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 = 8 | μ = 7.63 | σ = 0.99

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++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Rust Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fengvyi C++
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vthwang Java
YuriSpiridonov Python
zfang399 C++
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++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fengvyi C++
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vthwang Java
YuriSpiridonov Python
zfang399 C++
40 links | 26 authors | 10 languages

Videos

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

Similar Problems

3 similar problems

Solved On The Same Day

5 easy 4 medium 4 hard
14 solutions   October 3, 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