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