From d60fd1c180885c767a32134d76662ab51ca7fcc0 Mon Sep 17 00:00:00 2001 From: Shinjanee Gupta Date: Mon, 23 Feb 2026 21:59:04 -0800 Subject: [PATCH] Completed Trees-1 --- constructBinaryTree.py | 38 ++++++++++++++++++++++++++++++++++++++ validatebst.py | 25 +++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 constructBinaryTree.py create mode 100644 validatebst.py diff --git a/constructBinaryTree.py b/constructBinaryTree.py new file mode 100644 index 00000000..d09eb53a --- /dev/null +++ b/constructBinaryTree.py @@ -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) + \ No newline at end of file diff --git a/validatebst.py b/validatebst.py new file mode 100644 index 00000000..4690ce39 --- /dev/null +++ b/validatebst.py @@ -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')) + \ No newline at end of file