작심삼일

[LeetCode] 98 | Validate Binary Search Tree | Python 본문

스터디/코테

[LeetCode] 98 | Validate Binary Search Tree | Python

yun_s 2022. 8. 11. 20:50
728x90
반응형

문제 링크: https://leetcode.com/problems/validate-binary-search-tree/


문제

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

A valid BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

조건

  • The number of nodes in the tree is in the range [1, 104].
  • $-2^{31}$ <= Node.val <= $2^{31}$ - 1

내 풀이

node.val의 범위가 -inf부터 inf까지임을 참고한다.

매 노드를 확인하면서 그 노드가 현재 조건에 만족하는지(small < root.val < big)를 확인한다.

그 조건에 만족한다면 왼쪽 노드와 오른쪽 노드도 각각의 조건을 만족하는지를 확인한다.

Valid한 BST가 되려면 왼쪽 노드의 조건은 (small, root.val)이 되고, 오른쪽 노드의 조건은 (root.val, big)이 된다.


코드

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        def check(root, small, big):
            if not root:
                return True
            
            if not small < root.val < big:
                return False
            
            return check(root.left, small, root.val) and check(root.right, root.val, big)
        
        return check(root, -inf, inf)
728x90
반응형
Comments