[Leetcode] Validate Binary search Tree verification binary

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.

Confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

This verification binary search tree has many kinds of solutions, can use its own nature to do, that is, left < root < Right, can also be done by using the sequence traversal results for ordered series, we first look at the simplest one, is to use its own nature to do, the initialization of the system with the maximum and minimum value, In the recursive process to replace their own node values, with a long in place of int is to include the boundary condition of int, the code is as follows:

Solution One:

//recursion without inorder traversalclassSolution { Public:    BOOLIsvalidbst (TreeNode *root) {        returnIsvalidbst (Root, Long_min, Long_max); }    BOOLIsvalidbst (TreeNode *root,LongMnLongmx) {if(!root)return true; if(Root->val <= mn | | root->val >= mx)return false; returnIsvalidbst (Root->left, MN, Root->val) && Isvalidbst (Root->right, root->val, MX); }};

Let's look at the use of the middle sequence traversal to do, this method of thinking is very straightforward, through the middle sequence traversal all the node value into an array, and then to determine whether the array is ordered, the code is as follows:

Solution Two:

//recursionclassSolution { Public:    BOOLIsvalidbst (TreeNode *root) {        if(!root)return true; Vector<int>Vals;        Inorder (Root, Vals);  for(inti =0; I < vals.size ()-1; ++i) {if(Vals[i] >= vals[i +1])return false; }        return true; }    voidInorder (TreeNode *root, vector<int> &Vals) {        if(!root)return; Inorder (Root-Left , Vals); Vals.push_back (Root-val); Inorder (Root-Right , vals); }};

The following solution is similar to the above one, all using recursive middle sequence traversal, but the difference is not to put the traversal results into an array traversal to complete the comparison, but each time traversing to a new node and its previous node comparison, if not greater than the previous node then return FALSE, all the completion of the return of true. The code is as follows:

Solution Three:

//still recursionclassSolution { Public: TreeNode*Pre; BOOLIsvalidbst (TreeNode *root) {        intres =1; Pre=NULL;        Inorder (Root, res); if(res = =1)return true; Else false; }    voidInorder (TreeNode *root,int&Res) {        if(!root)return; Inorder (Root-Left , RES); if(!pre) Pre =Root; Else {            if(Root->val <= pre->val) res =0; Pre=Root; } inorder (Root-Right , res); }};

Of course, this problem can also be used in non-recursive return to do, need to use the stack, because the middle sequence traversal can be non-recursive implementation, so long as it is slightly modified on the above, the code is as follows:

Solution Four:

//non-recursion with StackclassSolution { Public:    BOOLIsvalidbst (TreeNode *root) {        if(!root)return true; Stack<TreeNode*>s; TreeNode*p =Root; TreeNode*pre =NULL;  while(P | |!S.empty ()) {             while(P) {S.push (P); P= p->Left ; } P=S.top ();            S.pop (); if(!pre) Pre =p; Else {                if(P->val <= Pre->val)return false; } Pre=p; P= p->Right ; }        return true; }};

Finally there is a method, because the middle sequence traversal also has a non-recursive and no stack implementation method, called the Morris traversal, you can refer to my previous blog binary tree inorder traversal two fork trees of the middle sequence traversal, this implementation method, although written more complex than the recursive version, But the advantage is O (1) space complexity, but my implementation method in this machine can pass, test on the OJ has runtime error, I find to find out where the problem is, regardless of the first paste up, perhaps can cause a great God's attention, help the younger brother to change the ha ~

Solution Five

//non-recursion without Stack, I don ' t know why it cannot pass OJ, which show Runtime error. Can anyone help me fix it? Thanks!classSolution { Public:    BOOLIsvalidbst (TreeNode *root) {        if(!root)return true; TreeNode*cur, *pre, *parent =NULL; Cur=Root;  while(cur) {if(!cur->Left ) {                if(Parent && parent->val >= cur->val)return false; Parent=cur; Cur= cur->Right ; } Else{Pre= cur->Left ;  while(Pre->right && pre->right! = cur) Pre = pre->Right ; if(!pre->Right ) {Pre->right =cur; Cur= cur->Left ; } Else{Pre->right =NULL; if(Parent->val >= Cur->val)return false; Parent=cur; Cur= cur->Right ; }            }        }        return true; }};

[Leetcode] Validate Binary search Tree verification binary

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.