0
Leetcode Problem 1740. Find Distance in a Binary Tree
1740. Find Distance in a Binary Tree
AI Mock Interview
Leetcode Solutions
One-Pass LCA-Based Distance Calculation
Solution Idea
Algorithm Steps
Code Implementation
Complexity Analysis
Perform a DFS traversal of the binary tree.
If the current node is null, return -1.
If the current node is one of the target nodes (p or q), return 0.
Recursively find the distance in the left subtree and the right subtree.
If both left and right distances are non-negative, the current node is the LCA.
If the current node is the LCA, calculate the total distance and store it in a global variable.
If only one of the distances is non-negative, return that distance plus one.
If neither p nor q is found in the current subtree, return -1.
Three-Pass LCA-Based Distance Calculation
Ask Question
Programming Language
Purpose:
General Question
Debug My Code
image/screenshot of info
(optional)
[+]
Full Screen
Loading...
Get Answer
Suggested Answer
Answer
Full Screen
Copy Answer Code
Loading...