[Leedcode 98] Validate Binary Search Tree

Source: Internet
Author: User

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.
    /*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { Public BooleanIsvalidbst (TreeNode root) {//[2147483647]//note that because the Val of root is of type int, it may be the maximum or minimum value, so the first setting is the largest or smallest to use long, note the type of the function parameter//the subject is very ingenious. Use the maximum and minimum values to limit the extent of the root node. The most critical is the correct definition of IsValid, which represents whether the value of root is between Min and Max//Another solution is to traverse the two-tree sequence and then detect if it is an incrementing array        returnIsValid (Root, (Long) Integer.min_value-1, (Long) integer.max_value+1); }     Public BooleanIsValid (TreeNode root,LongMinLongmax) {        if(root==NULL){            return true; }        LongVal= (Long) Root.val; if(val>min&&val<max) {            returnIsValid (Root.left,min,val) &&IsValid (Root.right,val,max); }Else return false; }}

[Leedcode 98] 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.