|
| 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