# 1740. Find Distance in a Binary Tree

<https://leetcode.com/problems/find-distance-in-a-binary-tree>

## Description

Given the root of a binary tree and two integers `p` and `q`, return *the **distance** between the nodes of value* `p` *and value* `q` *in the tree*.

The **distance** between two nodes is the number of edges on the path from one to the other.

**Example 1:**

![](https://assets.leetcode.com/uploads/2018/12/14/binarytree.png)

```
**Input:** root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 0
**Output:** 3
**Explanation:** There are 3 edges between 5 and 0: 5-3-1-0.
```

**Example 2:**

![](https://assets.leetcode.com/uploads/2018/12/14/binarytree.png)

```
**Input:** root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 7
**Output:** 2
**Explanation:** There are 2 edges between 5 and 7: 5-2-7.
```

**Example 3:**

![](https://assets.leetcode.com/uploads/2018/12/14/binarytree.png)

```
**Input:** root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 5
**Output:** 0
**Explanation:** The distance between a node and itself is 0.
```

**Constraints:**

* The number of nodes in the tree is in the range `[1, 104]`.
* `0 <= Node.val <= 109`
* All `Node.val` are **unique**.
* `p` and `q` are values in the tree.

## ac

```java
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jaywin.gitbook.io/leetcode/solutions/1740-find-distance-in-a-binary-tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
