#1740
Medium Algorithms Find distance in a binary tree
Hash Table Tree Depth-First Search Breadth-First Search Binary Tree
74.3% acceptance
Mar 31, 2026
485
19
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.
Solution
Rust
Time O(n)
Space O(n)
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn find_distance(root: Option<Rc<RefCell<TreeNode>>>, p: i32, q: i32) -> i32 {
if p == q { return 0; }
fn lca(node: &Option<Rc<RefCell<TreeNode>>>, p: i32, q: i32) -> Option<Rc<RefCell<TreeNode>>> {
if let Some(n) = node {
let val = n.borrow().val;
if val == p || val == q { return node.clone(); }
let left = lca(&n.borrow().left, p, q);
let right = lca(&n.borrow().right, p, q);
if left.is_some() && right.is_some() { return node.clone(); }
if left.is_some() { left } else { right }
} else { None }
}
fn depth(node: &Option<Rc<RefCell<TreeNode>>>, target: i32, d: i32) -> i32 {
if let Some(n) = node {
if n.borrow().val == target { return d; }
let l = depth(&n.borrow().left, target, d + 1);
if l != -1 { return l; }
depth(&n.borrow().right, target, d + 1)
} else { -1 }
}
let ancestor = lca(&root, p, q);
depth(&ancestor, p, 0) + depth(&ancestor, q, 0)
}
}