Skip to content

Commit

Permalink
Merge pull request #24 from Bill0412/patch-5
Browse files Browse the repository at this point in the history
Create 1740.Find-Distance-in-a-Binary-Tree_v2.cpp
  • Loading branch information
wisdompeak authored Dec 25, 2021
2 parents 6879d33 + 7138bc1 commit b639b72
Showing 1 changed file with 34 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* 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 {
int lcaDepth = -1, pDepth, qDepth;
TreeNode* lcaNode;
int lowestCommonAncestor(TreeNode* root, int p, int q, int depth) {
if(!root) return 0;

int count = lowestCommonAncestor(root->left, p, q, depth + 1) +
lowestCommonAncestor(root->right, p, q, depth + 1) +
(root->val == p) + (root->val == q);

if(root->val == p) pDepth = depth;
if(root->val == q) qDepth = depth;
if(count == 2 && lcaDepth == -1) lcaDepth = depth;

return count;
}
public:
int findDistance(TreeNode* root, int p, int q) {
lowestCommonAncestor(root, p, q, 0);

return (pDepth - lcaDepth) + (qDepth - lcaDepth);
}
};

0 comments on commit b639b72

Please sign in to comment.