EasyBinary TreeRecursionDepth-First Search

Path Sum

LeetCode
1 approach, code in all languages

You are given the root of a binary tree and an integer target. Determine whether the tree contains any root-to-leaf path whose node values add up exactly to the target. A leaf is a node with no children.

Return true if such a path exists and false otherwise. An empty tree contains no path and should return false.

Example 1

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], target = 22

Output: true

The path 5 -> 4 -> 11 -> 2 sums to 22, so a qualifying root-to-leaf path exists.

Example 2

Input: root = [1,2,3], target = 5

Output: false

The only root-to-leaf sums are 1+2=3 and 1+3=4, neither of which equals 5.

Constraints

  • The number of nodes is in the range [0, 5 * 10^3]
  • -10^3 ≤ Node.val ≤ 10^3
  • -10^3 ≤ target ≤ 10^3
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now