Detailed analysis of leetcode: recover Binary Search Tree [tree]

Source: Internet
Author: User

 

Recover the tree without changing its structure.

Note:
A solution using O (n) space is pretty straight forward. cocould you devise a constant space solution?

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

Here are a few knowledge points to note. It is a good question to evaluate the knowledge of BST. 1. How can we find out where the two are in disorder? If we look at the tree directly, it seems that the relationship is a bit fuzzy; then, consider a nature, through the middle order traversal, You can output BST in ascending order, eg: 12 3 4 56 7, here, we can change the position randomly to form a 16 3 4 5 2 7, 6 and 2 split the series into three parts, each segment remains in ascending order when it is independent (the departments with headers and tails do not contain elements), but 6> 3, 5> 2. This indicates that the first occurrence of PRE> cur occurs, PRE is the wrong node, and the second occurrence of PRE> cur, cur is the wrong node, you can record it.

2. elements that may change positions are adjacent to each other in the sorting process (not necessarily adjacent in the tree structure diagram). The PRE> cur mentioned in Section 1 overlaps with each other only once;

The Code is as follows:

Class solution {PRIVATE: treenode * Pre, * node1, * node2; // declare as a member variable, so that each function can be accessed without repeated creation; void inorder (treenode * root) {If (root = NULL) return; inorder (root-> left); If (pre! = NULL & Pre-> Val> root-> Val) {// The second (and the last) occurrence is the correct position. This avoids judgment, directly overwrite node2 = root; If (node1 = NULL) // use null to indicate whether it is the first time that node1 = pre;} Pre = root; inorder (root-> right);} public: void recovertree (treenode * root) {pre = NULL; node2 = node1 = NULL; inorder (Root ); node1-> Val ^ = node2-> val; node2-> Val ^ = node1-> val; node1-> Val ^ = node2-> val ;}};



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.