Oliver's Blog
Ctrlk
  • 🤩Welcome!
  • Projects
    • RISC Game
    • Mini Amazon
    • HTTP Caching Proxy
    • Course Enrollment App
    • Fitness Tracker App
    • Voice Shopping Assistant
    • Graphics Town
  • Algo
    • Binary Search
    • Linked List
    • Recursion Basics
    • Binary Tree
      • 1. Traversal
      • 2. Classical Questions
      • 3. Binary Search Tree
        • Insert Node in a Binary Search Tree
        • Remove Node in Binary Search Tree
        • Validate Binary Search Tree
        • Trim a Binary Search Tree
        • Search Range in Binary Search Tree
        • Inorder Successor in BST
        • Binary Search Tree Iterator
        • Recover Binary Search Tree
      • 4. Divide and Conquer
      • Convert Sorted Array to Binary Search Tree
      • Path Sum
      • Lowest Common Ancestor of a Binary Search Tree
      • Sum of Left Leaves
      • Minimum Absolute Difference in BST
      • Minimum Distance Between BST Nodes
      • Convert Sorted List to Binary Search Tree
      • Range Sum of BST
      • Kth Smallest Element in a BST
      • Find Largest Value in Each Tree Row
    • Sorting
    • Two Pointers
    • Queue & Stack
    • Hash Table
    • Heap & Priority Queue
    • BFS
    • Array
    • String
    • Math
    • Dynamic Programming
    • LeetCode vs. LintCode Table
  • React Notes
    • Optimizing Performance in React
  • Golang Notes
    • Basics
    • Official Tutorial Notes
  • Miscellaneous
    • Traveling to China During a Global Pandemic
Powered by GitBook
On this page
  1. Algo
  2. Binary Tree
  3. 3. Binary Search Tree

Validate Binary Search Tree

ID: 98; medium; 验证二叉查找树

LogoValidate Binary Search Tree - LeetCodeLeetCode
LogoLintCode 炼码 - 更高效的学习体验!www.lintcode.com

Solution 1 (Java)

PreviousRemove Node in Binary Search TreeNextTrim a Binary Search Tree

Last updated 4 years ago

Was this helpful?

Was this helpful?

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: True if the binary tree is BST, or false
     */
    public boolean isValidBST(TreeNode root) {
        return isValidBSTHelper(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    private boolean isValidBSTHelper(TreeNode root, long min, long max) {
        if (root == null)
            return true;
        if (root.val <= min || root.val >= max)
            return false;
        boolean isLeftValid = isValidBSTHelper(root.left, min, root.val);
        boolean isRightValid = isValidBSTHelper(root.right, root.val, max);
        return isLeftValid && isRightValid;
    }
}