Skip to content

Commit cbe8951

Browse files
committed
validate-binary-search-tree sol (py)
1 parent dfdc227 commit cbe8951

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

β€Žvalidate-binary-search-tree/hi-rachel.pyβ€Ž

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,73 @@
1+
"""
2+
λͺ¨λ“  μ™Όμͺ½ μ„œλΈŒνŠΈλ¦¬λŠ” ν˜„μž¬ λ…Έλ“œλ³΄λ‹€ μž‘μ•„μ•Ό ν•˜κ³ ,
3+
λͺ¨λ“  였λ₯Έμͺ½ μ„œλΈŒνŠΈλ¦¬λŠ” ν˜„μž¬ λ…Έλ“œλ³΄λ‹€ 컀야 ν•œλ‹€.
4+
5+
이걸 μœ„ν•΄μ„œ λ²”μœ„(min/max)λ₯Ό μž¬κ·€λ‘œ 내렀보내야 ν•œλ‹€.
6+
7+
TC: O(n), λͺ¨λ“  λ…Έλ“œ 1λ²ˆμ”© 탐색
8+
SC: O(h), μž¬κ·€ 호좜 μŠ€νƒ, hλŠ” 트리 높이
9+
"""
10+
11+
from typing import Optional
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+
19+
class Solution:
20+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
21+
def validate(node, low, high):
22+
if not node:
23+
return True # λΉ„μ–΄μžˆλŠ” λ…Έλ“œλŠ” BST
24+
# ν˜„μž¬ λ…Έλ“œκ°€ λ²”μœ„ 밖이면 BST 쑰건 μœ„λ°°
25+
if not (low < node.val < high):
26+
return False
27+
# μ™Όμͺ½μ€ μ΅œλŒ€κ°’μ„ ν˜„μž¬ λ…Έλ“œλ³΄λ‹€ μž‘κ²Œ μ œν•œ
28+
# 였λ₯Έμͺ½μ€ μ΅œμ†Œκ°’μ„ ν˜„μž¬ λ…Έλ“œλ³΄λ‹€ 크게 μ œν•œ
29+
return (validate(node.left, low, node.val) and
30+
validate(node.right, node.val, high))
31+
32+
return validate(root, float('-inf'), float('inf'))
33+
34+
35+
"""
36+
μŠ€νƒ 풀이
37+
38+
- BSTμ—μ„œ μ€‘μœ„ μˆœνšŒν•˜λ©΄ 항상 μ˜€λ¦„μ°¨μˆœμ΄μ–΄μ•Ό ν•œλ‹€λŠ” μ„±μ§ˆμ„ μ΄μš©ν•œ 방법
39+
- μ€‘μœ„ 순회: μ™Όμͺ½ β†’ ν˜„μž¬ λ…Έλ“œ β†’ 였λ₯Έμͺ½
40+
- BSTλŠ” μ€‘μœ„ 순회 μ‹œ 값이 항상 증가해야 ν•˜λ―€λ‘œ, (μ˜€λ¦„μ°¨μˆœ)
41+
이전 λ…Έλ“œ(prev)보닀 ν˜„μž¬ λ…Έλ“œ 값이 μž‘κ±°λ‚˜ κ°™μœΌλ©΄ 잘λͺ»λœ BST
42+
43+
TC: O(n), λͺ¨λ“  λ…Έλ“œ 1λ²ˆμ”© 탐색
44+
SC: O(h), μ΅œλŒ€ μŠ€νƒ 깊이 = 트리 높이
45+
"""
46+
47+
class Solution:
48+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
49+
stack = []
50+
prev = None # 이전 μ€‘μœ„ 순회 κ°’
51+
52+
while stack or root:
53+
# μ™Όμͺ½ λκΉŒμ§€ 탐색
54+
while root:
55+
stack.append(root)
56+
root = root.left
57+
58+
root = stack.pop()
59+
60+
# 이전 값보닀 μž‘κ±°λ‚˜ κ°™μœΌλ©΄ BST μœ„λ°˜
61+
if prev is not None and root.val <= prev:
62+
return False
63+
prev = root.val
64+
65+
# 였λ₯Έμͺ½μœΌλ‘œ 이동
66+
root = root.right
67+
68+
return True
69+
70+
171
# O(n) time, O(n) space
272

373
# Definition for a binary tree node.

0 commit comments

Comments
Β (0)