Skip to content

Commit de3bb9e

Browse files
Leetcode accepted
1 parent 5f91555 commit de3bb9e

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Lowest Common Ancestor of a Binary Search Tree
2+
# https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
3+
4+
# Definition for a binary tree node.
5+
# class TreeNode(object):
6+
# def __init__(self, x):
7+
# self.val = x
8+
# self.left = None
9+
# self.right = None
10+
11+
class Solution(object):
12+
def postOrder(self, node, p, q, answer):
13+
if not node:
14+
return
15+
leftFound = self.postOrder(node.left, p, q, answer)
16+
rightFound = self.postOrder(node.right, p, q, answer)
17+
# if found in left subtree and right sub tree
18+
if (leftFound and rightFound):
19+
# then append to the answer
20+
answer.append(node)
21+
return
22+
# if one of the nodes is the value
23+
if (node == p or node == q):
24+
# then current node is lca
25+
if (leftFound or rightFound):
26+
answer.append(node)
27+
return
28+
# else return true since we found node in the sub tree.
29+
return True
30+
# if we find nothing, then we just propogate the answer from the below subtree to pass it to root.Ellipsis
31+
if (leftFound or rightFound):
32+
return True
33+
34+
35+
def lowestCommonAncestor(self, root, p, q):
36+
answer = []
37+
self.postOrder(root, p, q, answer)
38+
return answer[0]
39+
"""
40+
:type root: TreeNode
41+
:type p: TreeNode
42+
:type q: TreeNode
43+
:rtype: TreeNode
44+
"""
45+

0 commit comments

Comments
 (0)