Loading...
Given the root of a binary tree whose node values are unique, and two distinct values a and b that are both guaranteed to appear in the tree, return the distance between the two nodes holding those values: the number of edges on the unique path connecting them.
Parent pointers are not available, only the root.
Your function receives root as a TreeNode, the node type is provided for you, with val, left and right fields.
The examples below write the tree as its level-order traversal, where null marks a missing child of a listed node and trailing nulls are omitted. That is only how the input is displayed; the decoding is done for you.
Node.val ≤105; all node values are unique.a = b, and both values appear in the tree.The path is 9 -> 3 -> 20, which uses 2 edges.
The path is 9 -> 3 -> 20 -> 15.
3 is an ancestor of 7; the path is 3 -> 20 -> 7.
Click "Run" to test with sample cases or "Submit" to run all tests.