Skip to content

Commit c719829

Browse files
committed
solved : validate-binary-search-tree
1 parent bd601c6 commit c719829

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+
# ๋ชจ๋“  ๋…ธ๋“œ๊ฐ€ ์กฐ๊ฑด ๋งŒ์กฑํ•˜๋ฉด True
4+
5+
class TreeNode:
6+
def __init__(self, val=0, left=None, right=None):
7+
self.val = val
8+
self.left = left
9+
self.right = right
10+
11+
class Solution:
12+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
13+
stack = []
14+
# ์ตœ์†Œ๊ฐ’, ์ตœ๋Œ€๊ฐ’ ๊ตฌํ•  ๋•Œ ์‚ฌ์šฉ
15+
# float('-inf') : ์Œ์˜ ๋ฌดํ•œ๋Œ€
16+
# float('inf') : ์–‘์˜ ๋ฌดํ•œ๋Œ€
17+
prev = float('-inf')
18+
current = root
19+
20+
# current๊ฐ€ ์กด์žฌํ•˜๊ฑฐ๋‚˜ stack์ด ๋น„์–ด์žˆ์ง€ ์•Š์€ ํ•œ ๊ณ„์† ์ง€์†
21+
while current or stack :
22+
while current:
23+
stack.append(current)
24+
current = current.left
25+
current = stack.pop()
26+
if current.val <= prev:
27+
return False
28+
prev = current.val
29+
current = current.right
30+
return True
31+

0 commit comments

Comments
ย (0)