#C9194. Root-to-Leaf Path Sum in Binary Tree
Root-to-Leaf Path Sum in Binary Tree
Root-to-Leaf Path Sum in Binary Tree
You are given a binary tree represented as an array of nodes. Each node is described by a tuple \( (\text{value},\; \text{left_index},\; \text{right_index}) \), where \(-1\) denotes a missing child. The tree is zero-indexed and its root is at index 0.
Your task is to determine whether there exists a root-to-leaf path along which the sum of the node values equals a given target sum \(S\), i.e.,
\[
S = \sum_{i=1}^{k} v_i
\]
where \(v_i\) are the node values along the path. If such a path exists, print Yes
; otherwise, print No
.
Note: A leaf is a node with no children.
inputFormat
The input is read from stdin and has the following format:
- The first line contains two integers,
targetSum
andn
, wheretargetSum
is the sum to be checked andn
is the number of nodes in the tree. - The next
n
lines each contain three integers:value
,left_index
, andright_index
. A value of-1
for an index indicates that the corresponding child does not exist. The tree is built with node 0 as the root.
outputFormat
The output should be printed to stdout and consists of a single line: Yes
if there exists a root-to-leaf path with a sum equal to targetSum
, and No
otherwise.
10 0
No