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
38 changes: 38 additions & 0 deletions constructBinaryTree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Time Complexity : O(n)
# Space Complexity : O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : elements to the left and right of root in inorder array are used to form the left and right subtree.

# 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 __init__(self):
self.preorder_idx = 0

def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
def tree(left, right):
if left > right:
return None

root_val = preorder[self.preorder_idx]
root = TreeNode(root_val)
self.preorder_idx += 1

root.left = tree(left, inorder_idx_map[root_val] - 1)
root.right = tree(inorder_idx_map[root_val] + 1, right)

return root


inorder_idx_map = {}

for idx, val in enumerate(inorder):
inorder_idx_map[val] = idx

return tree(0, len(preorder) - 1)

25 changes: 25 additions & 0 deletions validatebst.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Time Complexity : O(n)
# Space Complexity : O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach: Recursively ensure each node’s value lies within its allowed low and high range.

# 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 validate(self, root: Optional[TreeNode], low: int, high: int) -> bool:
if not root:
return True

if root.val <= low or root.val >= high:
return False

return self.validate(root.left, low, root.val) and self.validate(root.right, root.val, high)

def isValidBST(self, root: Optional[TreeNode]) -> bool:
return self.validate(root, -float('inf'), float('inf'))