Skip to content

Commit 1574698

Browse files
committed
add solution: validate-binary-search-tree
1 parent 095994a commit 1574698

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
'''
2+
# 98. Validate Binary Search Tree
3+
4+
check if is a valid BST.
5+
- the left value is smaller than the current value
6+
- the right value is greater than the current value
7+
8+
๐Ÿ‘‰ all left and right subtrees must also valid continuously.
9+
so, we need to check the low & high bound recursively. (not only check current node & immediate children)
10+
11+
## base case
12+
- if the node is None, return True (empty tree is valid BST)
13+
- valid node value has range of left < node.val < right, if not, return False
14+
- recursively check the left and right subtree, update the low & high.
15+
'''
16+
class Solution:
17+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
18+
def dfs(node, low = float('-inf'), high = float('inf')):
19+
if not node:
20+
return True
21+
if not (low < node.val < high):
22+
return False
23+
24+
return dfs(node.left, low, node.val) and dfs(node.right, node.val, high)
25+
26+
return dfs(root)

0 commit comments

Comments
ย (0)