A binary tree of GPS waypoint ids is given in level-order form. Line 1 is a single line of space-separated tokens (null marking a missing child; every non-null node contributes exactly two following tokens for its children). Every value that appears in the tree is distinct. Line 2 contains two distinct integers u v, both guaranteed to be values that appear somewhere in the tree.
Print the distance (the number of edges on the unique path) between the node whose value is u and the node whose value is v.
Line 1: space-separated level-order tokens describing the binary tree (integers and the token null); all values are distinct.
Line 2: two distinct integers u v, each guaranteed to be present in the tree.
A single integer: the number of edges on the path between the two named nodes.
Example 1
Input
1 2 3 4 5 4 5
Expected
2
Explanation
4 and 5 are both children of 2 (their LCA). Distance = depth(4)+depth(5)-2*depth(2) = 2+2-2*1 = 2.
Example 2
Input
1 2 3 4 5 1 5
Expected
2
Explanation
1 is an ancestor of 5 (1 -> 2 -> 5), so their LCA is 1 itself. Distance = depth(5) - depth(1) = 2 - 0 = 2.
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 →