Given a binary tree and two integer values p and q, write a recursive function to find the distance between the two nodes with values p and q.
The distance between two nodes is the number of edges on the path between them.
It is guaranteed that both p and q exist in the tree and that all node values are unique.
Function Signature
def find_distance(tree: list[int | None], p: int, q: int) -> int:
Rules
-
tree
is the level-order encoding of the binary tree.
tree[0]
is the root value. The remaining entries give the left child and then the right child of each non-null node, level by level from left to right, with
None
for a missing child. A missing node has no entries for its children, and trailing
None
values may be left out.
-
The path may climb toward the root and then descend, so the two nodes do not need to be ancestor and descendant.
Constraints
-
The number of nodes in the tree is in the range
[2, 10^4]
.
-
-10^5 <= Node.val <= 10^5
-
All node values are unique.
-
p != q
-
Both
p
and
q
exist in the tree.
Examples
All three examples use this tree, encoded as [3,5,1,6,2,0,8,None,None,7,4]:
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
Input: tree = [3,5,1,6,2,0,8,None,None,7,4], p = 5, q = 1
Output: 2
The path is 5, 3, 1. Both nodes are children of the root, one edge each, so the distance is 1 + 1 = 2.
Input: tree = [3,5,1,6,2,0,8,None,None,7,4], p = 5, q = 4
Output: 2
Node 4 is below node 5, so the path goes straight down: 5, 2, 4. That is 2 edges.
Input: tree = [3,5,1,6,2,0,8,None,None,7,4], p = 7, q = 8
Output: 5
The path is 7, 2, 5, 3, 1, 8. It climbs three edges from 7 to the root and descends two edges to 8, for a distance of 5.