Skip to content

Commit 7a9762f

Browse files
committed
solve: validateBinarySearchTree
1 parent 6952b38 commit 7a9762f

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Time Complexity: O(n) - visit every node once during the inorder traversal
2+
# Space Complexity: O(n) - store all node values in an array during traversal
3+
4+
class Solution:
5+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
6+
# helper to do an inorder traversal and return a list of values
7+
def inorder(node):
8+
if not node:
9+
return []
10+
# in-order: left -> current -> right
11+
return inorder(node.left) + [node.val] + inorder(node.right)
12+
13+
# get the in-order traversal of the tree
14+
arr = inorder(root)
15+
16+
# if there are duplicates, it's not a valid BST
17+
if len(arr) != len(set(arr)):
18+
return False
19+
20+
# if it's sorted in strictly increasing order, it's a valid BST
21+
return arr == sorted(arr)

0 commit comments

Comments
 (0)