Method One: If BST, the order is convenient after the order, increment. It is possible to see if the sequence traversal is incremented to determine
1 classSolution {2 Public:3 BOOLIsvalidbst (TreeNode *root) {4 5 if(Root = =NULL)6 return true;7vector<int>result;8Stack<treenode*>St;9 Tentreenode* p =Root; One A //inorder Traverse - while(P! = NULL | | st.size ()! =0) - { the while(P! =NULL) - { - St.push (p); -p = p->Left ; + } - + if(!st.empty ()) A { atp =st.top (); - St.pop (); -Result.push_back (p->val); -p = p->Right ; - } - } in - //Check if it is Ascend to for(inti =0; I < result.size ()-1; i++) + { - if(Result[i] < result[i+1]) the ; * Else $ return false;Panax Notoginseng } - return true; the + } A};
Method Two: Using recursion, to determine the current node value, whether in the upper and lower bounds, for the root node, there is no boundary. And then recursive judgment.
1 classSolution {2 Public:3 BOOLIsvalidbst (TreeNode *root) {4 returnIsvalidbst (Root, Int_min, Int_max);5 } 6 BOOLIsvalidbst (TreeNode *root,intMinintmax)7 { 8 if(Root = NULL)return true;9 Ten if((Root->val < max) && (Root->val > Min) && OneIsvalidbst (root->left, Min, root->val) && AIsvalidbst (Root->right, root->val, max) - ) - return true; the Else - return false; - } -};
[Leetcode] Validate Binary Search Tree