Tuesday, November 3, 2015

[leetcode] Validate Binary Search

4 things I learnt:
1. Double.MIN_VALUE is the closest positive number to Zero.
2. Leetcode online judge thinks binary search tree doesn't have duplicate in it.
  - and it's right, here is a quote i found online.
  Universal Definition of a Binary Search Tree involves storing and search for a key based on traversing a data structure in one of two directions. In the pragmatic sense, that means if the value is <>, you traverse the data structure in one of two 'directions'. So, in that sense, duplicate values don't make any sense at all.
3. Watch out test case contains Integer extreme value, need to check if my code handles it in the future.
4. Validate binary search tree... it looks trivial, but it actually requires some carefulnesses.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class Solution {
    public boolean isValidBST(TreeNode root) {
        return isValidBSTRec(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    
    private boolean isValidBSTRec(TreeNode root, long min, long max){
        if (root == null) return true;
        if ((long)root.val <= min || (long)root.val >= max) return false;
        return isValidBSTRec(root.left, min, root.val)&&isValidBSTRec(root.right, root.val, max);
    }
}

No comments:

Post a Comment