A binary tree of paint-can color codes is given in level-order form (a single line of space-separated tokens, null marking a missing child; every non-null node contributes exactly two following tokens for its children).
A branch is any path of nodes in the tree that are connected by parent-child edges, where the path may bend at most once at a single common node (a route from one node up to a shared ancestor and back down into the other side, or a straight downward path). A branch is called uniform if every node on it has the exact same value.
Print the number of edges in the longest uniform branch. (A single node, by itself, is a uniform branch with 0 edges.)
Line 1: space-separated level-order tokens describing the binary tree (integers and the token null).
A single integer: the number of edges in the longest uniform branch. If the tree is empty, print 0.
Example 1
Input
5 5 5 null 5
Expected
3
Explanation
Root 5's left child is 5 (arm length 1 continuing into a grandchild 5, arm length 2), and the right child is also 5 (arm length 1). Bending at the root gives 2 + 1 = 3 edges of value 5.
Example 2
Input
1 2 2 3 3 null 3
Expected
0
Explanation
No edge joins two nodes of equal value: the root 1 differs from both 2s, and each 3 sits directly beneath a 2. So no uniform branch spans even a single edge — the longest uniform branch is one lone node, giving 0 edges.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →