Skip to content

Commit ff57c5b

Browse files
committed
feat: implement validation for binary search tree
1 parent faf633b commit ff57c5b

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
from typing import Optional
2+
3+
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+
class Solution:
12+
def checker(self, node: Optional[TreeNode], low: float, high: float) -> bool:
13+
"""(Helper)
14+
์ฃผ์–ด์ง„ ๋…ธ๋“œ๊ฐ€ ์œ ํšจํ•œ BST ๋…ธ๋“œ์ธ์ง€ ๊ฒ€์ฆํ•˜๋Š” ํ•จ์ˆ˜
15+
16+
Args:
17+
node (Optional[TreeNode]): ๊ฒ€์ฆํ•  node ๊ฐ์ฒด
18+
low (float): node.val์ด ๋  ์ˆ˜ ์žˆ๋Š” ์ตœ์†Œ๊ฐ’
19+
high (float): node.val์ด ๋  ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€๊ฐ’
20+
21+
Returns:
22+
bool: node๊ฐ€ ์œ ํšจํ•œ BST ๋…ธ๋“œ์ธ์ง€ ์—ฌ๋ถ€
23+
"""
24+
if node is None:
25+
return True
26+
value = node.val
27+
left, right = node.left, node.right
28+
if not (low < value < high):
29+
return False
30+
return self.checker(left, low, value) and self.checker(right, value, high)
31+
32+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
33+
"""
34+
ํ˜„์žฌ ํŠธ๋ฆฌ๊ฐ€ ์˜ฌ๋ฐ”๋ฅธ binary tree์ธ์ง€ ๊ฒ€์ฆํ•˜๋Š” ํ•จ์ˆ˜
35+
36+
checker ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ ํŠธ๋ฆฌ์˜ ๋ชจ๋“  ๋…ธ๋“œ๊ฐ€ BST์˜ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š”์ง€ ๊ฒ€์ฆํ•จ.
37+
checker ํ•จ์ˆ˜๋Š” ์žฌ๊ท€์ ์œผ๋กœ ํ˜ธ์ถœ๋˜๊ณ , ๊ฐ ๋…ธ๋“œ์˜ ๊ฐ’์ด ํ—ˆ์šฉ๋œ ๋ฒ”์œ„ ๋‚ด์— ์žˆ๋Š”์ง€ ํ™•์ธํ•จ.
38+
์ดํ›„ ์™ผ์ชฝ ์ž์‹ ๋…ธ๋“œ๋Š” ํ˜„์žฌ ๋…ธ๋“œ์˜ ๊ฐ’๋ณด๋‹ค ์ž‘์€ ๋ฒ”์œ„๋กœ, ์˜ค๋ฅธ์ชฝ ์ž์‹ ๋…ธ๋“œ๋Š” ํ˜„์žฌ ๋…ธ๋“œ์˜ ๊ฐ’๋ณด๋‹ค ํฐ ๋ฒ”์œ„๋กœ ๊ฒ€์ฆํ•จ.
39+
40+
Args:
41+
root (Optional[TreeNode]): ๊ฒ€์ฆ๋˜์ง€ ์•Š๋Š” tree ๊ฐ์ฒด
42+
43+
Returns:
44+
bool: ์˜ฌ๋ฐ”๋ฅธ binary tree์ธ์ง€ ์—ฌ๋ถ€
45+
"""
46+
return self.checker(root, -float("inf"), float("inf"))

0 commit comments

Comments
ย (0)