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
36 changes: 36 additions & 0 deletions construct-binary-tree-from-preorder-and-inorder-traversal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'''
Time Complexity : O(2)
Space Complexity : O(n)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No
'''
# 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 buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
if len(preorder) == 0:
return None
rootVal = preorder[0]
rootIdx = -1
for i in range(len(inorder)):
if inorder[i] == rootVal:
rootIdx = i
break

root = TreeNode(rootVal)
inleft = inorder[:rootIdx]
inRight = inorder[rootIdx+1:]

preleft = preorder[1:len(inleft)+1]
preRight = preorder[len(inleft)+1:]

root.left = self.buildTree(preleft, inleft)
root.right = self.buildTree(preRight, inRight)

return root


40 changes: 40 additions & 0 deletions validate-binary-search-tree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
'''
Time Complexity : O(2)
Space Complexity : O(n)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No
'''

# 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
import copy
class Solution:
def __init__(self):
self.flag = True
self.prev = None

def helper(self, root):
if root == None:
return

self.helper(root.left)

# write condition to make the flag false
if self.prev != None and self.prev.val >= root.val:
self.flag = False
self.prev = root

self.helper(root.right)

def isValidBST(self, root: Optional[TreeNode]) -> bool:

if root == None:
return True

self.helper(root)

return self.flag