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