[Leetcode] Recover Binary Search Tree

Source: Internet
Author: User

Elements of a binary search tree (BST) is swapped by mistake.

Recover the tree without changing its structure.

Note:
A Solution using O ( N) space is pretty straight forward. Could you devise a constant space solution?

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

Hide TagsTree Depth-first Search

Ideas:

The solution to the O (n) space is to open an array of pointers, sequence traversal, store the node pointer in the array, and then look for two
In the reverse position, first from the back to find the first reverse position, and then from the back to find the second reverse position, exchange these two
The value of the pointer.
The middle sequence traversal generally needs to use the stack, the space is also O (n), how can not use the stack? Morris in sequence traversal.

Method one: Middle sequence traversal

classSolution { Public:        voidRecovertree (TreeNode *root) {Vector<TreeNode*>result; Stack<TreeNode*>St; TreeNode* p =Root; //inorder Traverse             while(P! = NULL | | st.size ()! =0)            {                 while(P! =NULL)                    {St.push (P); P= p->Left ; }                if(!St.empty ()) {P=St.top ();                    St.pop ();                    Result.push_back (P); P= p->Right ; }} TreeNode* R1 = NULL, *r2 =NULL;  for(inti =0; I < result.size ()-1; i++)            {                if(Result[i]->val > result[i+1]->val) {R1=Result[i];  Break; }            }             for(inti = result.size ()-1; I >=1; i--)            {                if(Result[i]->val < result[i-1]->val) {R2=Result[i];  Break; }            }            //swap R1 and R2 ' s value            intTMP = r1->Val; R1->val = r2->Val; R2->val =tmp; }};

[Leetcode] Recover 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.