File tree Expand file tree Collapse file tree 1 file changed +21
-0
lines changed
validate-binary-search-tree Expand file tree Collapse file tree 1 file changed +21
-0
lines changed Original file line number Diff line number Diff line change 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 )
You can’t perform that action at this time.
0 commit comments