본문 바로가기
Programming/Algorithm

[leetcode] ValidateBinarySearchTree

by 읽고 쓰는 개발자 2020. 11. 29.

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

 

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

import exam.TreeNode;
public class ValidateBinarySearchTree {
    public static void main(String[] args) {
        TreeNode node6 = new TreeNode(1);
        TreeNode node7 = new TreeNode(3);
        TreeNode root = new TreeNode(2,node6, node7);
        System.out.println(isValidBST(root));
    }

//    dfs
    public static boolean isValidBST(TreeNode root) {
        return isValidBST(root, Long.MAX_VALUE, Long.MIN_VALUE);
    }

    public static boolean isValidBST(TreeNode root, long maxVal, long minVal) {
        if (root == null) return true;
        if(root.val >= maxVal || root.val <= minVal ) return false;
        return isValidBST(root.left, root.val, minVal) && isValidBST(root.right, maxVal, root.val);

    }
}

'Programming > Algorithm' 카테고리의 다른 글

[leetcode] WordDictionary  (0) 2020.11.29
[leetcode] ValidParentheses  (0) 2020.11.29
[leetcode] RotateList  (0) 2020.11.29
[leetcode] RomanToInt  (0) 2020.11.29
[leetcode] PopulatingNextRightPointersinEachNode  (0) 2020.11.29