---
# System prepended metadata

title: LC 236. Lowest Common Ancestor of a Binary Tree
tags: [medium, leedcode, LCA, c++]

---

# LC 236. Lowest Common Ancestor of a Binary Tree

### [Problem link](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/)

###### tags: `leedcode` `medium` `c++` `LCA`

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the <a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank">definition of LCA on Wikipedia</a>: &ldquo;The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow  **a node to be a descendant of itself** ).&rdquo;

**Example 1:** 
<img alt="" src="https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" style="width: 200px; height: 190px;" />
```
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
```

**Example 2:** 
<img alt="" src="https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" style="width: 200px; height: 190px;" />
```
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
```

**Example 3:** 

```
Input: root = [1,2], p = 1, q = 2
Output: 1
```

 **Constraints:** 

- The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.
- <code>-10<sup>9</sup> <= Node.val <= 10<sup>9</sup></code>
- All <code>Node.val</code> are  **unique** .
- <code>p != q</code>
- <code>p</code> and <code>q</code> will exist in the tree.

## Solution 1
#### C++
```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) {
        if (root == nullptr || root == p || root == q) {
            return root;
        }
        TreeNode *left = lowestCommonAncestor(root->left, p, q);
        TreeNode *right = lowestCommonAncestor(root->right, p, q);
        if (left && right) {
            return root;
        }
        if (left == nullptr) {
            return right;
        }
        return left;
    }
};
```

>### Complexity
>|             | Time Complexity | Space Complexity |
>| ----------- | --------------- | ---------------- |
>| Solution 1  | O(n)            | O(n)             |

## Note
sol1:
[Ref](https://www.bilibili.com/video/BV1W44y1Z7AR/?spm_id_from=333.788&vd_source=088937f16fb413336c0cb260ed86a1c3)
![image](https://hackmd.io/_uploads/Hy4MUWN8A.png)
