bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 1740. Find Distance in a Binary Tree

1740. Find Distance in a Binary Tree

Leetcode Solutions

One-Pass LCA-Based Distance Calculation

  1. Perform a DFS traversal of the binary tree.
  2. If the current node is null, return -1.
  3. If the current node is one of the target nodes (p or q), return 0.
  4. Recursively find the distance in the left subtree and the right subtree.
  5. If both left and right distances are non-negative, the current node is the LCA.
  6. If the current node is the LCA, calculate the total distance and store it in a global variable.
  7. If only one of the distances is non-negative, return that distance plus one.
  8. If neither p nor q is found in the current subtree, return -1.
UML Thumbnail

Three-Pass LCA-Based Distance Calculation

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...