Skip to content

Commit 814dc18

Browse files
committed
feat: add validate binary search tree solution
1 parent 838598b commit 814dc18

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from typing import Optional
2+
3+
4+
# Definition for a binary tree node.
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+
12+
class Solution:
13+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
14+
"""
15+
- Idea: ๊ฐ ๋…ธ๋“œ ๊ฐ’์˜ ํ—ˆ์šฉ ๋ฒ”์œ„๋ฅผ ์ •ํ•˜๊ณ  ์žฌ๊ท€์ ์œผ๋กœ ๊ฒ€์‚ฌํ•œ๋‹ค.
16+
1. BST์˜ ์ •์˜ ํ™œ์šฉ
17+
์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์˜ ๋ชจ๋“  ๊ฐ’์€ ํ˜„์žฌ ๋…ธ๋“œ ๊ฐ’๋ณด๋‹ค ์ž‘๊ณ , ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์˜ ๋ชจ๋“  ๊ฐ’์€ ํ˜„์žฌ ๋…ธ๋“œ ๊ฐ’๋ณด๋‹ค ํผ.
18+
2. ์ดˆ๊ธฐ๊ฐ’์˜ ๋ฒ”์œ„๋ฅผ (-inf, inf)๋กœ ์„ค์ •
19+
3. ๊ฐ ๋…ธ๋“œ์˜ ๊ฐ’์„ ๊ฒ€์‚ฌํ•˜๊ณ , ๋ฒ”์œ„๋ฅผ ์—…๋ฐ์ดํŠธํ•ด์„œ ์žฌ๊ท€์ ์œผ๋กœ ์„œ๋ธŒ ํŠธ๋ฆฌ ํ™•์ธ
20+
- Time Complexity: O(n). n์€ ํŠธ๋ฆฌ์˜ ๋…ธ๋“œ ์ˆ˜
21+
๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ํ•œ๋ฒˆ์”ฉ ๋ฐฉ๋ฌธํ•œ๋‹ค.
22+
- Space Complexity: O(h). h๋Š” ํŠธ๋ฆฌ์˜ ๋†’์ด
23+
์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ์ด ํŠธ๋ฆฌ์˜ ๋†’์ด๋งŒํผ ๊ณต๊ฐ„์„ ํ•„์š”๋กœ ํ•œ๋‹ค.
24+
ํŽธํ–ฅ๋œ ํŠธ๋ฆฌ๋ผ๋ฉด O(n)์ด ํ•„์š”ํ•˜๋‹ค.
25+
"""
26+
27+
def isValid(node: Optional[TreeNode], low: float, high: float) -> bool:
28+
if not node:
29+
return True
30+
if not (node.val < high and node.val > low):
31+
return False
32+
33+
return isValid(node.left, low, node.val) and isValid(
34+
node.right, node.val, high
35+
)
36+
37+
return isValid(root, float("-inf"), float("inf"))

0 commit comments

Comments
ย (0)