엔지니어 게시판
LeetCode 솔루션 분류

[8/11] 98. Validate Binary Search Tree

컨텐츠 정보

본문

Medium
11369956Add to ListShare

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

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.

 

Example 1:

Input: root = [2,1,3]
Output: true

Example 2:

Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.

 

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -231 <= Node.val <= 231 - 1
Accepted
1,560,125
Submissions
5,014,795

관련자료

댓글 2

학부유학생님의 댓글

  • 익명
  • 작성일
Runtime: 85 ms, faster than 24.13% of Python3 online submissions for Validate Binary Search Tree.
Memory Usage: 16.5 MB, less than 46.02% of Python3 online submissions for Validate Binary Search Tree.
# 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], floor = float('-inf'), ceiling=float('inf')) -> bool:
        
        return not root or (floor<root.val<ceiling and 
                           self.isValidBST(root.left, floor, root.val) and 
                           self.isValidBST(root.right, root.val, ceiling))

재민재민님의 댓글

  • 익명
  • 작성일
Runtime: 15 ms, faster than 77.39% of C++ online submissions for Validate Binary Search Tree.
Memory Usage: 21.8 MB, less than 30.99% of C++ online submissions for Validate Binary Search Tree.
class Solution {
public:
    
    bool helper(TreeNode* root, long min, long max) {
        if(!root)
            return true;
        
        if( min < root->val && root->val < max ) 
            return helper(root->left, min, root->val) && helper(root->right, root->val, max);
        else
            return false;
    }
    
    bool isValidBST(TreeNode* root) {        
        return helper(root, LONG_MIN, LONG_MAX);        
    }
};
전체 396 / 8 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 182 명
  • 오늘 방문자 5,488 명
  • 어제 방문자 5,697 명
  • 최대 방문자 11,134 명
  • 전체 회원수 1,095 명
알림 0