Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added python code of finding lowest common ancestor (LCA) of two given nodes in the tree. #613

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions PYTHON/608_N_Queen.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Name: Zain Ali Shah
// Date : 30 October 2022

class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
# recusive
if n == 0:
return 0
res = []
board = [['.'] * n for t in range(n)]
self.do_solveNQueens(res, board, n)
return res

def do_solveNQueens(self, res, board, num):
if num == 0:
res.append([''.join(t) for t in board])
return
ls = len(board)
pos = ls - num
check = [True] * ls
for i in range(pos):
for j in range(ls):
if board[i][j] == 'Q':
check[j] = False
step = pos - i
if j + step < ls:
check[j + step] = False
if j - step >= 0:
check[j - step] = False
break
for j in range(ls):
if check[j]:
board[pos][j] = 'Q'
self.do_solveNQueens(res, board, num - 1)
board[pos][j] = '.'


if __name__ == '__main__':
# begin
s = Solution()
print s.solveNQueens(4)
51 changes: 51 additions & 0 deletions PYTHON/612_LCAinGraph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Author : Zain Ali Shah
# Date : 31/10/2022
'''
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

Given the following binary search tree: root = [3,5,1,6,2,0,8,null,null,7,4]

_______3______
/ \
___5__ ___1__
/ \ / \
6 _2 0 8
/ \
7 4
Example 1:

Input: root, p = 5, q = 1
Output: 3
Explanation: The LCA of of nodes 5 and 1 is 3.
'''

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""

if not root:
return None

if root == p or root == q:
return root

l = self.lowestCommonAncestor(root.left, p, q)
r = self.lowestCommonAncestor(root.right, p, q)

if l and r:
return root
return l if l else r