Find Distance in a Binary Tree — LeetCode 1740 Python Solution

MediumLeetCode PremiumTreeDepth-First SearchBreadth-First SearchHash TableBinary Tree
Problem
#1740
Reading time
5 min

The problem

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

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.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findDistance(self, root: Optional[TreeNode], p: int, q: int) -> int:
        def lca(root, p, q):
            if root is None or root.val in [p, q]:
                return root
            left = lca(root.left, p, q)
            right = lca(root.right, p, q)
            if left is None:
                return right
            if right is None:
                return left
            return root

        def dfs(root, v):
            if root is None:
                return -1
            if root.val == v:
                return 0
            left, right = dfs(root.left, v), dfs(root.right, v)
            if left == right == -1:
                return -1
            return 1 + max(left, right)

        g = lca(root, p, q)
        return dfs(g, p) + dfs(g, q)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1740. Find Distance in a Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1740. Find Distance in a Binary Tree?
LeetCode 1740. Find Distance in a Binary Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 1740. Find Distance in a Binary Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1740. Find Distance in a Binary Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1740. Find Distance in a Binary Tree cover?
LeetCode 1740. Find Distance in a Binary Tree is tagged Tree, Depth-First Search, Breadth-First Search, Hash Table and Binary Tree on LeetCode.
Is LeetCode 1740. Find Distance in a Binary Tree a premium problem?
Yes. LeetCode 1740. Find Distance in a Binary Tree is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview