Binary Tree Path Sum

Hard
binary-tree dfs path-sum
Problem Description

Given a binary tree and a target sum, determine if there exists a root-to-leaf path where the sum of node values equals the target.

Input Format
First line contains target sum. Second line contains space-separated node values in level-order (use -1 for null nodes).
Output Format
Print "YES" if such path exists, "NO" otherwise
Constraints
1 ≤ number of nodes ≤ 1000, -1000 ≤ node values ≤ 1000
Sample Input/Output
Input:
22
5 4 8 11 -1 13 4 7 2 -1 -1 -1 1
Output:
YES
Explanation

Path 5→4→11→2 sums to 22

Solution Hints
  • Read carefully: Understand input/output format and constraints
  • Start simple: Think of brute force solution first, then optimize
  • Edge cases: Consider empty inputs, single elements, max constraints
  • Data structures: Choose arrays, hash maps, sets based on problem needs
  • Time complexity: Ensure your solution fits within time limits
  • Test examples: Verify logic with provided sample inputs
300
Points
2000ms
Time Limit
256MB
Memory Limit
Code Editor
Register to Submit
Register to Access Code Editor

Create a free account to solve coding problems and track your progress.

Register Now
Feedback