[Leetcode] Recover Binary Search Tree

Source: Internet
Author: User

As the note in the problem statement, this problem have a straight-forward O (n)-space solution, which is to genera Te the Inorder traversal results of the BST and then find the both nodes that violate the increasing trend and those is th E. requires to be swapped.

This link utilizes inorder traversal to find those, nodes without keeping all the results. However, inorder traversal implemented recursively would take at least O (LOGN) space and could even take O (n) space at the worst case. The code is rewritten as follows.

1 classSolution {2  Public:3     voidRecovertree (treenode*root) {4Pre = first = Second =NULL;5 inorder (root);6         if(first) {7             inttemp = FirstVal;8First--val = SecondVal;9Second, val =temp;Ten         } One     } A Private: -TreeNode *first, *second, *Pre; -     voidInorder (treenode*root) { the         if(!root)return; -Inorder (RootLeft ); -         if(Pre && Pre, Val > rootval) { -             if(!first) First =Pre; +Second =Root; -         } +Pre =Root; AInorder (RootRight ); at     } -};

So to come up with an O (1) -space Solution, we indeed has to turn to Morris traversal ...

[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.