Skip to content

Commit 2b13a80

Browse files
author
Partho Biswas
committed
236. Lowest Common Ancestor of a Binary Tree
1 parent fa3941c commit 2b13a80

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,7 @@ Check this [golden](https://tinyurl.com/ujopecz) post.
349349
|27| **[298. Binary Tree Longest Consecutive Sequence](https://tinyurl.com/rw2sqxr)**| [Python](https://tinyurl.com/wu6rdaw/298_Binary_Tree_Longest_Consecutive_Sequence.py)| **[Art 1](https://tinyurl.com/wmlq6md)** | Medium | DFS |
350350
|28| **[951. Flip Equivalent Binary Trees](https://tinyurl.com/wj4bqms)**| [Python](https://tinyurl.com/wu6rdaw/951_Flip_Equivalent_Binary_Trees.py)| **[Vid 1](https://tinyurl.com/uw378m8)**, [Art 1](https://tinyurl.com/r5d6jkk) | Medium | DFS |
351351
|29| **[528. Random Pick with Weight](https://tinyurl.com/vf8bruk)**| [Python](https://tinyurl.com/wu6rdaw/528_Random_Pick_with_Weight.py)| **[Vid 1](https://tinyurl.com/usd5r25)**, **[Art 1](https://tinyurl.com/rgwt57q)** | Medium | Very tricky |
352+
|30| **[236. Lowest Common Ancestor of a Binary Tree](https://tinyurl.com/y54e6gco)**| [Python](https://tinyurl.com/wu6rdaw/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py)| **[Vid 1](https://tinyurl.com/udf9oa9)**, **[Vid 2](https://tinyurl.com/stknbyu)**, **[Algoexpert.io](https://tinyurl.com/wwz4m5t)**, **[Official](https://tinyurl.com/yx28t8ff)**, **[Art 1](https://tinyurl.com/v86wcky)**, **[Art 2](https://tinyurl.com/tu7jdzq)**, **[Art 3](https://tinyurl.com/tgvyy7p)** | Medium | TODO: Check Again. Very Important |
352353

353354
</p>
354355
</details>
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode(object):
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.left = None
6+
# self.right = None
7+
8+
# https://tinyurl.com/tu7jdzq
9+
class Solution(object):
10+
def lowestCommonAncestor(self, root, p, q):
11+
"""
12+
:type root: TreeNode
13+
:type p: TreeNode
14+
:type q: TreeNode
15+
:rtype: TreeNode
16+
"""
17+
if not root:
18+
return None
19+
if p == root or q == root:
20+
return root
21+
left = self.lowestCommonAncestor(root.left, p, q)
22+
right = self.lowestCommonAncestor(root.right, p, q)
23+
if left and right:
24+
return root
25+
if not left:
26+
return right
27+
if not right:
28+
return left
29+
30+

0 commit comments

Comments
 (0)