We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Practice
  • Certification
  • Compete
  • Career Fair
  • Hiring developers?
  1. Practice
  2. Tutorials
  3. Cracking the Coding Interview
  4. Trees: Is This a Binary Search Tree?
  5. Discussions

Trees: Is This a Binary Search Tree?

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • ritianfitchett 3 years ago+ 0 comments

    If you want to just throw everything in the return statement, why have if statements at all? You could do this instead:

    boolean checkBST(Node root) {
            return checkBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
        }
        boolean checkBST(Node node, int min, int max) {
            return  (node == null) || 
                (min < node.data && node.data < max && 
                checkBST(node.left, min, node.data) && 
                checkBST(node.right, node.data, max));
        }
    

    I think you put the null check in an if statement in an attempt to avoid null pointer exceptions but remember that compilers "short circuit" boolean logic. If node == null, the program will not evaluate the rest of the statement because True or'd with anything is true and so NullPointerException is never thrown because no references to node beyond that ever occur.

    2|
    ParentPermalink
  • Contest Calendar
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature