#C6030. Product of Nodes with Two Children in a Binary Tree
Product of Nodes with Two Children in a Binary Tree
Product of Nodes with Two Children in a Binary Tree
You are given a binary tree represented in level order using a space‐separated string. For example, the tree 1 2 3
represents a tree with root 1
, left child 2
and right child 3
.
Your task is to compute the product of all nodes in the tree that have both a left and a right child. If a node does not have both children, it should not be included in the product. Note that if the tree is empty (represented by a single token null
), the product is defined to be 1
. If no node in the tree has both children, output 0
.
Important: The answer might be large, so make sure to use appropriate data types.
The mathematical formulation is as follows: \[ \text{Answer} = \begin{cases} 1, & \text{if the tree is empty} \\ \prod_{N \in T \text{ having both children}} N.val, & \text{if at least one such node exists} \\ 0, & \text{otherwise} \end{cases} \]
inputFormat
The input is read from standard input (stdin) and consists of a single line containing space-separated tokens representing the binary tree in level order. Use the token null
to denote missing children. For example:
null
represents an empty tree.1
represents a single-node tree with root value 1.1 2 3
represents a tree with root 1, left child 2, and right child 3.
outputFormat
Print a single integer to standard output (stdout) which is the product of all nodes that have both a left and a right child. If no such node exists (and the tree is non-empty), print 0. If the tree is empty, print 1.
## samplenull
1