#K42547. Binary Tree Diameter
Binary Tree Diameter
Binary Tree Diameter
You are given a binary tree described by n nodes and a list of edges. Each edge is represented by three integers v, l, and r, where v is the value of the current node, and l and r are the values of its left and right children respectively. A value of 0 indicates that the child does not exist.
The diameter of a binary tree is defined as the number of edges in the longest path between two nodes. Mathematically, for any node, if the depth of its left subtree is L and the depth of its right subtree is R, then the candidate diameter at that node is given by:
\( d = \max\{L + R\} \)
Your task is to compute the diameter of the binary tree.
inputFormat
The input is read from standard input (stdin
) and has the following format:
- The first line contains an integer n denoting the number of nodes in the tree. If n = 0, the tree is empty.
- Then follow n lines. Each line contains three integers: v l r, where v is the value of a node, and l and r denote the value of its left and right child respectively (a value of 0 indicates no child).
outputFormat
Output the diameter of the binary tree (i.e. the number of edges in the longest path between any two nodes) to standard output (stdout
).
5
1 2 3
2 4 5
3 0 0
4 0 0
5 0 0
3