Skip to content

Commit 08f4da9

Browse files
committed
validate binary search tree solution (py)
1 parent b991376 commit 08f4da9

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# O(n) time, O(n) space
2+
3+
# Definition for a binary tree node.
4+
# class TreeNode:
5+
# def __init__(self, val=0, left=None, right=None):
6+
# self.val = val
7+
# self.left = left
8+
# self.right = right
9+
10+
# ์ขŒ์ธก ์„œ๋ธŒ ํŠธ๋ฆฌ๋กœ ๋‚ด๋ ค๊ฐˆ ๋–„:
11+
# - ํ•˜ํ•œ๊ฐ’: ๋ถ€๋ชจ ๋…ธ๋“œ์˜ ํ•˜ํ•œ๊ฐ’
12+
# - ์ƒํ•œ๊ฐ’: ๋ถ€๋ชจ ๋…ธ๋“œ์˜ ๊ฐ’
13+
# ์šฐ์ธก ์„œ๋ธŒ ํŠธ๋ฆฌ๋กœ ๋‚ด๋ ค๊ฐˆ ๋•Œ:
14+
# - ํ•˜ํ•œ๊ฐ’: ๋ถ€๋ชจ ๋…ธ๋“œ์˜ ๊ฐ’
15+
# - ์ƒํ•œ๊ฐ’: ๋ถ€๋ชจ ๋…ธ๋“œ์˜ ์ƒํ•œ๊ฐ’
16+
17+
class Solution:
18+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
19+
def dfs(node, low, high):
20+
if not node:
21+
return True
22+
if not (low < node.val < high):
23+
return False
24+
return dfs(node.left, low, node.val) and dfs(node.right, node.val, high)
25+
26+
return dfs(root, float('-inf'), float("inf"))
27+

0 commit comments

Comments
ย (0)