[leetcode] validate-binary-search-tree

김_리트리버·2020년 9월 4일
0

[알고리즘]

목록 보기
8/47

https://leetcode.com/problems/validate-binary-search-tree/

var isValidBST = function(root) {
    if(!root) return true;
    return validate(root, null, null);
};

function validate(node, min, max){
// 현재값이 왼쪽보다 작으면 false 
    if(min !== null && node.val <= min) return false;
// 현재값이 오른쪽보다 크면 true 
    if(max !== null && node.val >= max) return false;

    // everything from the left should be less than current node,
    // we do not check min here
// left 를 확인하기 때문에 min 은 null 인상태 
// 왼쪽 부모노드 보다 작은지 확인 
    if(node.left && !validate(node.left, min, node.val)) return false;
    // everything from the right should be greater than current node,
    // we do not check max here
    if(node.right && !validate(node.right, node.val, max)) return false;

    return true;
}
profile
web-developer

0개의 댓글