• 欢迎光临~

# [Oracle] LeetCode 1740 Find Distance in a Binary Tree

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.

### Solution

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode() : val(0), left(nullptr), right(nullptr) {}
*     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
*     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
TreeNode* LCA(TreeNode* rt, int p, int q){
if(!rt) return NULL;
if(rt->val==p || rt->val==q)return rt;
TreeNode* leftrt = LCA(rt->left, p,q);
TreeNode* rightrt = LCA(rt->right, p, q);
if(leftrt&&rightrt)return rt;
if(!leftrt && !rightrt)return NULL;
return leftrt?leftrt:rightrt;
}

int get_depth(TreeNode* rt, int v, int dep){
if(!rt) return 0;
if(rt->val==v) return dep;
return get_depth(rt->right, v, dep+1)+get_depth(rt->left, v, dep+1);
}

public:
int findDistance(TreeNode* root, int p, int q) {
TreeNode* lca = LCA(root, p, q);
return get_depth(lca,p,0)+get_depth(lca,q,0);
}
};
``````