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 ;}};