#K80047. Longest Distinct Path in a Binary Tree
Longest Distinct Path in a Binary Tree
Longest Distinct Path in a Binary Tree
You are given a binary tree where each node contains an integer value. Your task is to find the length of the longest path starting from the root such that all the node values in the path are distinct.
A path is defined as a sequence of nodes starting at the root and moving only to the left or right child. If you visit a node with a value that has already appeared in the current path, you must stop the path at that node.
Mathematically, if we denote the set of node values along the path by \(S\), then the path is valid if and only if \(|S| = \text{length of the path}\). You need to output the maximum length of such a valid path.
Example 1:
Input: 1 2 3 4 2 null null</p>Explanation: The binary tree is constructed as follows: 1 /
2 3 /
4 2 The longest valid path is 1 -> 2 -> 4 which has length 3. Output: 3
Example 2:
Input: 1 2 1</p>Explanation: The tree: 1 /
2 1 The longest valid path is 1 -> 2 with length 2. Output: 2
inputFormat
The input is provided via standard input (stdin) as a single line containing the level order traversal of the binary tree. Each value is separated by a space. The string "null" represents a missing (empty) child. For example:
1 2 3 4 2 null null
This represents the following binary tree:
1 / \ 2 3 / \ 4 2
outputFormat
Output a single integer to standard output (stdout) which is the length of the longest path starting from the root where all the node values are distinct.
For the sample above, the output would be:
3## sample
1 2 3 4 2 null null
3