Min distance between two given nodes of a Binary Tree | Practice
Given a binary tree and two node values, find the minimum distance between them.
Example: tree with nodes, a=4, b=5 → distance = 2
Sample Input
—
Sample Output
—
Constraints
- 1 <= N <= 10^4
- 1 <= a, b <= N
Topics
LCA + Distance
Find LCA, then sum distances from LCA to each node.
function findDist(root, a, b) {
function lca(node) {
if (!node || node.val===a || node.val===b) return node;
const l = lca(node.left), r = lca(node.right);
return l && r ? node : l || r;
}
function dist(node, target, d) {
if (!node) return -1;
if (node.val === target) return d;
const l = dist(node.left, target, d+1);
return l !== -1 ? l : dist(node.right, target, d+1);
}
const ancestor = lca(root);
return dist(ancestor, a, 0) + dist(ancestor, b, 0);
}
Time: O(n) | Space: O(h)
Saved in this browser only. Private to you.