Skip to content
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
31 changes: 31 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#98. Validate Binary Search Tree

# Definition for a binary tree node.
import math
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
min = -math.inf
max = math.inf

return self.validateBST(root,min,max)

def validateBST(self,root,min,max):

if root.val<=min or root.val=>max:
return False
validateLeftNode = True
if root.left != None:
validateLeftNode = validateBST(root.left, min, root.val)

if not validateLeftNode:
return False
validateRightNode = True
if root.right != None:
validateRightNode = validateBST(root.right, root.val, max)

return validateRightNode
37 changes: 37 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#Construct Binary Tree from Preorder and Inorder Traversal

# Time complexity -> 2(O(n)) -> On as it traverse through each element twice
# Space complexity -> O(h) -> The stack space of the depth

# Logic -> Use inorder array to find left and subtrees while preorder tree provides the current node

# 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:
rootIndex = 0
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
InorderIndexmap = {}
self.rootIndex=0
for i in range(0,len(inorder)):
InorderIndexmap[inorder[i]] = i

return self.helper(InorderIndexmap,preorder,0,len(preorder)-1)



def helper(self, InorderIndexmap, preorder, leftIndex, rightIndex):
if leftIndex > rightIndex:
return None
rootval = preorder[self.rootIndex]
self.rootIndex+=1
rootNode = TreeNode(rootval)
rootIndexInInOrder = InorderIndexmap[rootval]
rootNode.left = self.helper(InorderIndexmap,preorder,leftIndex,rootIndexInInOrder-1)

rootNode.right = self.helper(InorderIndexmap,preorder,rootIndexInInOrder+1,rightIndex)

return rootNode