Skip to content

Commit 27524b5

Browse files
committed
Beat 82.69% in Runtime, 98.90% in memory, only use O(1) memory
1 parent 3dd58a3 commit 27524b5

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

98. Validate Binary Search Tree.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def isValidBST(self, root):
9+
return self.valid_root(root)
10+
11+
def find_min(self, root):
12+
if root == None:
13+
return
14+
while root.left != None:
15+
root = root.left
16+
return root.val
17+
18+
def find_max(self, root):
19+
if root == None:
20+
return
21+
while root.right != None:
22+
root = root.right
23+
return root.val
24+
25+
def valid_root(self, root):
26+
if root.left == None and root.right == None:
27+
return True
28+
if root.left == None:
29+
bool_condition = root.val < self.find_min(root.right) and self.valid_root(
30+
root.right
31+
)
32+
return bool_condition
33+
34+
if root.right == None:
35+
bool_condition = root.val > self.find_max(root.left) and self.valid_root(
36+
root.left
37+
)
38+
return bool_condition
39+
40+
general_case = (
41+
root.val > self.find_max(root.left)
42+
and root.val < self.find_min(root.right)
43+
and self.valid_root(root.left)
44+
and self.valid_root(root.right)
45+
)
46+
return general_case

0 commit comments

Comments
 (0)