#K12821. Path Sum Check in Binary Tree
Path Sum Check in Binary Tree
Path Sum Check in Binary Tree
Given a binary tree and two integers \(A\) and \(B\), you are to determine whether there exists a root-to-leaf path in the tree for which the sum of the node values is exactly equal to \(A\) or \(B\). The binary tree is provided in level order where the keyword null
represents a missing node.
A root-to-leaf path is defined as a sequence of nodes starting from the root node and ending at any leaf node (a node with no children). Let \(S\) be the sum of the node values along that path. The task is to check if \(S = A\) or \(S = B\).
For example, if the tree is given by the level order array:
5 4 8 11 null 13 4 7 2 null null null 1
and \(A = 22\) and \(B = 26\), then one valid root-to-leaf path is: 5 -> 4 -> 11 -> 2
with a sum of \(22\), so the answer is True
.
inputFormat
The input is given via standard input with two lines:
- The first line contains the level order traversal of the binary tree. Node values are separated by spaces and missing nodes are represented by the string
null
. - The second line contains two space-separated integers \(A\) and \(B\).
You can assume that the tree contains at least one node.
outputFormat
Output a single line to standard output: True
if there exists a root-to-leaf path whose sum is equal to either \(A\) or \(B\), or False
otherwise.
5 4 8 11 null 13 4 7 2 null null null 1
22 26
True