Skip to content

Commit 06de308

Browse files
authored
Update 1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II.cpp
1 parent 1f4100f commit 06de308

File tree

1 file changed

+12
-24
lines changed

1 file changed

+12
-24
lines changed

Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II.cpp

Lines changed: 12 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,35 +8,23 @@
88
* };
99
*/
1010
class Solution {
11-
int count = 0;
11+
TreeNode* ret = NULL;
1212
public:
1313
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
1414
{
15-
TreeNode* ret = lca(root, p, q);
16-
if (count!=2) return NULL;
17-
else return ret;
15+
int a = dfs(root, p, q);
16+
return ret;
1817
}
1918

20-
TreeNode* lca(TreeNode* root, TreeNode* p, TreeNode* q)
19+
int dfs(TreeNode* root, TreeNode* p, TreeNode* q)
2120
{
22-
if (root==NULL) return NULL;
23-
24-
TreeNode* L = lca(root->left,p,q);
25-
TreeNode* R = lca(root->right,p,q);
26-
27-
if (root==p || root==q)
28-
{
29-
count++;
30-
return root;
31-
}
32-
33-
if (L&&R)
34-
return root;
35-
else if (!L&&R)
36-
return R;
37-
else if (L&&!R)
38-
return L;
39-
else
40-
return NULL;
21+
if (root==NULL) return 0;
22+
int left = dfs(root->left, p, q);
23+
int right = dfs(root->right, p, q);
24+
int self = (root==p || root==q);
25+
int count = left+right+self;
26+
if (count==2 && ret==NULL)
27+
ret = root;
28+
return count;
4129
}
4230
};

0 commit comments

Comments
 (0)