We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 6952b38 commit 7a9762fCopy full SHA for 7a9762f
validate-binary-search-tree/yolophg.py
@@ -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