|
| 1 | +""" |
| 2 | +[Problem] |
| 3 | +https://leetcode.com/problems/validate-binary-search-tree/ |
| 4 | +
|
| 5 | +[Brainstorming] |
| 6 | +BST가 유효한지를 검증하는 문제. |
| 7 | +1 <= number of nodes <= 10^4(100,000) |
| 8 | +
|
| 9 | +[Plan] |
| 10 | +1. Tree를 DFS를 이용하여 만든다. |
| 11 | +2. 실제로 입력을 넣어보며, 존재하지 않는 경우 False를 반환한다. |
| 12 | +""" |
| 13 | +from typing import Optional |
| 14 | +class TreeNode: |
| 15 | + def __init__(self, val=0, left=None, right=None): |
| 16 | + self.val = val |
| 17 | + self.left = left |
| 18 | + self.right = right |
| 19 | + |
| 20 | +class Solution: |
| 21 | + """ |
| 22 | + Attempt 1 - My Solution (incorrect) |
| 23 | + 이 풀이의 경우, 자기 자신과 자기 자식 노드들 까지만으로 한정한다. |
| 24 | + 따라서, BST를 제대로 검증할 수 없다. |
| 25 | + root = [5,4,6,null,null,3,7] 인 경우에는 검증할 수 없다. (Edge Case) |
| 26 | + """ |
| 27 | + def isValidBST1(self, root: Optional[TreeNode]) -> bool: |
| 28 | + invalid_flag = False |
| 29 | + def dfs(node:Optional[TreeNode])->None: |
| 30 | + nonlocal invalid_flag |
| 31 | + if invalid_flag: |
| 32 | + return |
| 33 | + |
| 34 | + if not node: |
| 35 | + return |
| 36 | + |
| 37 | + if node.left and node.left.val > node.val: |
| 38 | + invalid_flag = True |
| 39 | + return |
| 40 | + if node.right and node.right.val < node.val: |
| 41 | + invalid_flag = True |
| 42 | + return |
| 43 | + |
| 44 | + dfs(node.left) |
| 45 | + dfs(node.right) |
| 46 | + |
| 47 | + dfs(root) |
| 48 | + return not invalid_flag |
| 49 | + """ |
| 50 | + Attempt 2 - Another Solution |
| 51 | + ref: https://www.algodale.com/problems/validate-binary-search-tree |
| 52 | + [Complexity] |
| 53 | + N: number of nodes in trees |
| 54 | + Time: O(N) => Traverse all nodes in the tree. |
| 55 | + Space: worst case: O(N), best case: O(log N) |
| 56 | + """ |
| 57 | + |
| 58 | + def isValidBST(self, root:Optional[TreeNode])->bool: |
| 59 | + def dfs(node:Optional[TreeNode], min_limit:int, max_limit:int)->bool: |
| 60 | + if not node: |
| 61 | + return True |
| 62 | + if not (min_limit < node.val < max_limit): |
| 63 | + return False |
| 64 | + |
| 65 | + return dfs(node.left, min_limit, node.val) and dfs(node.right, node.val, max_limit) |
| 66 | + |
| 67 | + |
0 commit comments