Find Distance In a Binary Tree
The problem
Given the root of a binary tree and two integers p and q, return the distance between the two nodes with values p and q.
The distance between two nodes in a tree is the number of edges on the shortest path between them.
**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.
**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.
**Input **: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 5
- 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.
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(val) : data(val), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
int findDistance(TreeNode* root, int p, int q) {
//Your Code Goes Here
}
};java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int data;
* TreeNode left;
* TreeNode right;
* TreeNode(int val) { data = val; left = null, right = null }
* }
**/
class Solution {
public int findDistance(TreeNode root, int p, int q) {
//Your Code Goes Here
}
}python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.data = val
# self.left = left
# self.right = right
class Solution(object):
def findDistance(self, root, p, q):
"""
:type root: Optional[TreeNode]
:type p: int
:type q: int
:rtype: int
"""
#Your Code Goes Herejavascript
/**
* Definition for a binary tree node.
* class TreeNode {
* constructor(val = 0, left = null, right = null){
* this.data = val;
* this.left = null;
* this.right = null;
* }
* }
**/
/**
* @param {TreeNode} root
* @param {number} p
* @param {number} q
* @return {number}
*/
class Solution {
findDistance(root, p, q) {
//your code goes here
}
}csharp
public class Solution {
public int FindDistance(TreeNode root, int p, int q) {
//Your Code Goes Here
}
}go
/*
Definition for a binary tree node.
type TreeNode struct {
Data int
Left *TreeNode
Right *TreeNode
}
*/
func findDistance(root *TreeNode, p int, q int) int {
}Stuck? Show a way to structure it+
- 01Confirm values are unique or clarify node identity
- 02Find the LCA with post-order recursion
- 03Compute distance from the LCA to each target
- 04Add the two distances and report missing-node behavior
Reference answer
Then expect these follow-ups
How would you solve it with parent pointers and BFS?
Tests: follow-up reasoning
What if one target is absent?
Tests: follow-up reasoning
Free to read · better with Enzo
Practice this out loud with Enzo
Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.
Next question