Leet Code - Validate Binary Search Tree

hatban·2022년 9월 28일
0

✔️ 문제 링크

https://leetcode.com/explore/learn/card/introduction-to-data-structure-binary-search-tree/140/introduction-to-a-bst/997/

이진 탐색 트리(BST, Binary Search Tree)

  • 이진 탐색 트리는 정렬된 이진 트리다
  • 노드의 왼쪽 하위 트리 : 노드의 값보다 작은 값을 가진 노드만 존재
  • 노드의 오른쪽 하위 트리 : 노드의 값보다 큰 값을 가진 노드만 존재
  • 중복 키 허용 x





이진 탐색 트리의 특징

BST는 Inorder Traversal 을 수행하며 키를 순서대로 가져올 수 있다



leetcode 문제에선 해당 트리가 BST를 만족하는지 물었다

코드

var isValidBST = function(root) {
    if(!root){
        return true;
    }
    
    function helper(root, min, max){
        if(!root) return true;
        
        if((min !== null && min>= root.val) || (max !== null && max <= root.val)){
            console.log('1')
            return false;
        }
        
        return helper(root.left, min, root.val) &&  helper(root.right, root.val, max);
    }
    
    return helper(root, null, null);
    
};

0개의 댓글