#K1546. Path Sum in Binary Tree
Path Sum in Binary Tree
Path Sum in Binary Tree
You are given a binary tree and a target integer \(S\). Determine if there exists a path from the root to any leaf such that the sum of the node values along the path equals \(S\).
The binary tree is provided in level-order traversal form. A value of -1 in the input represents a missing (null) node. For example, the level-order list [1, 2, 3, -1, -1, 4, 5]
represents the tree:
1
/ \
2 3
/ \
4 5
Your task is to implement an algorithm that returns "YES" if such a path exists, or "NO" otherwise. Use appropriate techniques such as depth-first search (DFS) or breadth-first search (BFS) to solve the problem efficiently.
inputFormat
The input is given via stdin in the following format:
- The first line contains two integers:
n
(the number of nodes in the tree) andS
(the target sum). - The second line contains
n
integers separated by spaces, representing the values of the nodes in level-order traversal. A value of -1 denotes a null node.
outputFormat
Output a single line to stdout which is either "YES" if there exists a root-to-leaf path with a sum equal to \(S\), or "NO" otherwise.
## sample5 6
1 2 3 4 5
YES
</p>