Validate Binary Search Tree - LeetCode

 

Validate Binary Search Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

class Solution:
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        
        if not root:
            return True
        
        if root.left:
            lmax = root.left
            while lmax.right:
                lmax = lmax.right
            if lmax.val >= root.val:
                return False
        
        if root.right:
            rmin = root.right
            while rmin.left:
                rmin = rmin.left
            if rmin.val <= root.val:
                return False
        
        return self.isValidBST(root.left) and self.isValidBST(root.right)

 

깔끔하고 최적인 코드를 쓴거같다. 하지만 다른 사람의 코드를 한 번 보긴 해야겠다.

 

def isValidBST(self, root, s=-inf, e=inf):
  if not root: return True
  if s >= root.val or e <= root.val: return False
  return self.isValidBST(root.left, s, root.val) and self.isValidBST(root.right, root.val, e)

 

ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ

진짜 leetcode discussion 하는 사람들은 뭐하는 사람들일까?

와 이걸 이렇게 풀수가 있구나..

이해도 잘되고 코드도 너무 간결하다. 대단하다...

+ Recent posts