Problem description:
Two elements of a binary search tree (BST) are swapped by mistake.
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.
OJ's binary tree serialization:
The serialization of a binary tree follows a level order traversal, where '# 'signiies a path Terminator where no node exists below.
Here's an example:
1 / 2 3 / 4 5
The above binary tree is serialized
"{1,2,3,#,#,4,#,#,5}". Analysis: The question indicates that there are two numbers in a cross-tree search tree, which are reversed and need to be found and restored to the normal order, one easy way to think of is to use the pointers of all nodes stored in the middle-order traversal, then traverse the Middle-order sequence to find two inverted nodes, and then exchange them, the following figure shows this idea on the Internet. When traversing in a central order, we can compare it with the previous node each time, find two inverted nodes P1 and P2, and then exchange them, you do not need to save the Middle-order traversal and then traverse it. The specific code is as follows:
/*** Definition for binary tree * struct treenode {* int val; * treenode * left; * treenode * right; * treenode (int x): Val (x ), left (null), right (null) {}*}; */class solution {public: treenode * Pre, * P1, * P2; void helper (treenode * root) {If (root = NULL) return; helper (root-> left); If (pre & Pre-> Val> root-> Val) // find the two numbers in the first reverse order {If (p1 = NULL) // first find P1 {p1 = pre; P2 = root ;} else // If two numbers in the reverse order of the second pair are found, P2 {P2 = root;} Pre = root; // initialize the pre to root helper (root-> right);} void recovertree (treenode * root) {If (root = NULL) return; pre = p1 = P2 = NULL; helper (Root); int temp; temp = p1-> val; P1-> val = P2-> val; P2-> val = temp; return ;}};