[Leetcode] [Java] Validate Binary Search Tree

Source: Internet
Author: User

Title:

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

    • The left subtree of a node contains only nodes with keys less than the node ' s key.
    • The right subtree of a node contains only nodes with keys greater than the node ' s key.
    • Both the left and right subtrees must also is binary search trees.
Test Instructions:

Given a binary tree, determine if it is a valid two-fork search tree (BST).

Suppose the binary search tree (BST) is defined as follows:

    • The node value on the left subtree of the node is less than this node value.
    • The node value on the right subtree of the node is greater than this node value.
    • The left and right subtree must be a two-fork search tree.

Algorithm Analysis:

Reference http://www.programcreek.com/2012/12/leetcode-validate-binary-search-tree-java/

By recursive method, each node is checked separately, the values on the left subtree of the node are smaller than the node values, and the values on the subtree are greater than the node values.


AC Code:

<span style= "Font-family:microsoft yahei;font-size:12px;" >public class Solution{Public    Boolean isvalidbst (TreeNode root)    {        return isvalidbst (Root, Double.negative_infinity, double.positive_infinity);        }    public boolean Isvalidbst (TreeNode p, double min, double max)    {        if (p==null)             return true;             if (p.val <= min | | p.val >= max)            return false;             Return Isvalidbst (p.left, Min, p.val) && Isvalidbst (P.right, P.val, max);}    } </span>


Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source

[Leetcode][java] Validate Binary Search Tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.