0% found this document useful (0 votes)
1 views

adv coding -304 assign 5

The document contains an assignment on advanced coding techniques, specifically focusing on searching algorithms. It includes code implementations for two problems from LeetCode: calculating the number of unique binary search trees and merging elements from two binary search trees. Each problem is accompanied by code snippets and outputs demonstrating the solutions.

Uploaded by

Matrix Gaming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

adv coding -304 assign 5

The document contains an assignment on advanced coding techniques, specifically focusing on searching algorithms. It includes code implementations for two problems from LeetCode: calculating the number of unique binary search trees and merging elements from two binary search trees. Each problem is accompanied by code snippets and outputs demonstrating the solutions.

Uploaded by

Matrix Gaming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

VU21CSEN0100304

D.V.J KRISHNAM RAJU

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]:

# defined array to store the output from 2 lists


ans1 = []
ans2 = []

# defined inorder function


def get_elem(node, tree):
if not node:
return
get_elem(node.left, tree)
if tree == '1':
ans1.append(node.val)
else:
ans2.append(node.val)
get_elem(node.right, tree)
# get the elements from two trees
get_elem(root1, '1')
get_elem(root2, '2')

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:

You might also like