"Leetcode" 98. Validate binary Search Tree-determine if two forks are sorted

Source: Internet
Author: User

First, Description:

Second, the idea:

Binary sort tree (BST), the result of the middle sequence traversal must be a non-descending sequence (from Baidu Encyclopedia);

In this case, the definition of BST is either greater than or small with, that is, the traversal result can only be an increment sequence, it can be judged whether the sequence of sequential traversal of the result series is an incremental sequence to determine if it is a legitimate BST;

Another approach is to use recursion;

Third, the code:

1, non-recursive, through the results of the middle sequence traversal judgment:

/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution {Privatelist<integer> list =NewArraylist<integer>();  Public BooleanIsvalidbst (TreeNode root) {inordertraversal (root); intSize =list.size (); if(Size==0 | | size==1){            return true; }         for(inti=0;i<size-1;i++){            if((List.get (i)) >= (List.get (i+1))){                return false; }        }        return true; }        //Middle Sequence Traversal     Public voidinordertraversal (TreeNode root) {if(root==NULL){            return; }Else{inordertraversal (root.left);            List.add (Root.val);        Inordertraversal (Root.right); }    }}

2. Recursion: Write again tomorrow

"Leetcode" 98. Validate binary Search Tree-determine if two forks are sorted

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.