adv coding -304 assign 5
adv coding -304 assign 5
ADVANCED CODING -2
ASSIGNMENT -5
SEARCHING TECHNIQUES
1. https://leetcode.com/problems/unique-binary-search-trees/
CODE:
class Solution:
def factorial(self,n):
if (n==0 or n==1):
return 1
return n*factorial(n-1)
def numTrees(self, n: int) -> int:
return int((self.factorial(2*n)/(self.factorial(n) * self.factorial( (2*n)
-n)))/(n+1))
SCREENSHOT:
OUTPUT:
2. https://leetcode.com/problems/all-elements-in-two-binary-
search-trees/
CODE:
#Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getAllElements(self, root1: TreeNode, root2: TreeNode) ->
List[int]:
ans = []
# print(ans1)
# ans.sort()
# use the two-pointer approach to get elems in single list
i,j = 0,0
while i<len(ans1) and j<len(ans2):
if ans1[i]<= ans2[j]:
ans.append(ans1[i])
i += 1
else:
ans.append(ans2[j])
j += 1
if j != len(ans2):
ans += ans2[j:]
if i != len(ans1):
ans += ans1[i:]
return ans
SCREENSHOTS:
OUTPUT: