Skip to content

Commit d90267f

Browse files
committed
add solution: validate-binary-search-tree
1 parent 67ed968 commit d90267f

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
'''
2+
๋ฌธ์ œ: ์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ๊ฐ€ ์œ ํšจํ•œ์ง€ ํ™•์ธํ•˜๊ธฐ
3+
ํ’€์ด: ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰(DFS)์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐ ๋…ธ๋“œ๊ฐ€ ์œ ํšจํ•œ ๋ฒ”์œ„ ๋‚ด์— ์žˆ๋Š”์ง€ ํ™•์ธ
4+
์‹œ๊ฐ„๋ณต์žก๋„: O(n)
5+
๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ํ•œ ๋ฒˆ์”ฉ ๋ฐฉ๋ฌธํ•˜๋ฏ€๋กœ ์ „์ฒด ์‹œ๊ฐ„๋ณต์žก๋„๋Š” O(n)์ด๋‹ค.
6+
๊ณต๊ฐ„๋ณต์žก๋„: O(h)
7+
์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ์ด ํŠธ๋ฆฌ์˜ ๋†’์ด h์— ๋น„๋ก€ํ•˜๋ฏ€๋กœ ์ „์ฒด ๊ณต๊ฐ„๋ณต์žก๋„๋Š” O(h)์ด๋‹ค.
8+
'''
9+
10+
11+
12+
# Definition for a binary tree node.
13+
# class TreeNode:
14+
# def __init__(self, val=0, left=None, right=None):
15+
# self.val = val
16+
# self.left = left
17+
# self.right = right
18+
class Solution:
19+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
20+
def dfs(root, ma, mi):
21+
if root == None:
22+
return True
23+
24+
if not (mi < root.val < ma):
25+
return False
26+
27+
return dfs(root.left, root.val, mi) and dfs(root.right, ma, root.val)
28+
29+
a = dfs(root, 10**100, -1*(10**100))
30+
return a
31+

0 commit comments

Comments
ย (0)