---
tags: leetcode
---
# [1644. Lowest Common Ancestor of a Binary Tree II](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-ii/)
---
# My Solution
## The Key Idea for Solving This Coding Question
## C++ Code
```cpp=
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
lca = nullptr;
dfs(root, p, q);
return lca;
}
private:
TreeNode *lca;
TreeNode *dfs(TreeNode *root, TreeNode *p, TreeNode *q) {
if (root == nullptr) {
return nullptr;
}
TreeNode *leftSubtree = dfs(root->left, p, q);
TreeNode *rightSubtree = dfs(root->right, p, q);
if (root == p || root == q) {
// root is either p or q.
if (leftSubtree != nullptr || rightSubtree != nullptr) {
// Case 1: Assume root is p. q is located in one of the subtrees.
// root is the LCA.
lca = root;
return root;
} else {
// Case 2: Assume root is p. q is not located in both of the subtrees.
return root;
}
}
// Case 3: p is located in one of the subtrees and q is in the other.
// Therefore, root is the LCA.
if (leftSubtree != nullptr && rightSubtree != nullptr) {
lca = root;
return root;
}
// Case 4: Both p and q are in one of the subtrees.
if (leftSubtree != nullptr) {
return leftSubtree;
}
if (rightSubtree != nullptr) {
return rightSubtree;
}
// Case 5: Both the subtrees don't have p nor q.
return nullptr;
}
};
```
## Time complexity
$O(n)$
$n$ is the number of nodes in the binary tree referred by `root`.
## Space complexity
$O(H)$
$H$ is the height of the binary tree referred by `root`.
# Miscellane
<!--
# Test Cases
```
[3,5,1,6,2,0,8,null,null,7,4]
5
1
```
```
[3,5,1,6,2,0,8,null,null,7,4]
5
4
```
```
[3,5,1,6,2,0,8,null,null,7,4]
5
10
```
-->