# 1740. Find Distance in a Binary Tree ###### tags: `Leetcode` `Medium` `Tree` `LCA` Link: https://leetcode.com/problems/find-distance-in-a-binary-tree/ ## 思路 和其他LCA的题差不多 稍微有一点变式 在findLCA里面 如果回传-1 说明当下subtree里面没有p/q或者已经找到答案了 ## Code ```java= class Solution { int result = 0; public int findDistance(TreeNode root, int p, int q) { if(p==q) return 0; findLCA(root, p, q); return result; } private int findLCA(TreeNode root, int p, int q){ if(root==null) return -1; int left = findLCA(root.left, p, q); int right = findLCA(root.right, p, q); if(root.val==p || root.val==q){ if (left < 0 && right < 0) { return 0; } result = 1 + (left >= 0 ? left : right); return -1; } if(left>=0 && right>=0){ result = left+right+2; return -1; } else if(left>=0) return left+1; else if(right>=0) return right+1; else return -1; } } ```