#C10558. Longest Path of Ones in a Binary Tree
Longest Path of Ones in a Binary Tree
Longest Path of Ones in a Binary Tree
You are given a binary tree where each node has a value of either 0 or 1. The tree is represented by n nodes. Each node is described by three integers: its value, the index of its left child, and the index of its right child. A child index of -1
indicates that there is no such child.
Your task is to find the length of the longest path that contains only nodes with value 1. In other words, for each node with value 1, you can consider a path that goes through that node, and its length is given by:
[ \text{length} = 1 + \text{(longest 1-path in left subtree)} + \text{(longest 1-path in right subtree)} ]
You need to output the maximum such length found in the entire tree.
inputFormat
The input is read from standard input (stdin) and has the following format:
n v0 l0 r0 ... vn-1 ln-1 rn-1
Here, n
is the number of nodes in the tree. Each of the following n
lines contains three integers separated by spaces:
v
: the value of the node (either 0 or 1),l
: the index of its left child (or -1 if there is no left child),r
: the index of its right child (or -1 if there is no right child).
outputFormat
The output is a single integer printed to standard output (stdout), representing the length of the longest path consisting entirely of 1s in the binary tree.
## sample1
1 -1 -1
1
</p>