Title: Two forks The tree has two nodes swapped values to restore them.
Ideas:
Because the middle sequence traversal is ordered, if the array after the sequence traversal is disorderly, the explanation is exchange. From the first after the first disorderly order, after the last one after the chaos, and then to swap the two values.
Thought of a very lame way.
The middle sequence traverses binary Tree inorder traversal, then finds two values in the array, then the middle order traversal to find the two values, swap. Although AC, but can't bear to look straight ah.
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: voidInorder (TreeNode *root, vector<int> &perm)//Middle sequence traversal gets array { if(Root = NULL)return ; Stack<treenode *>STA; Sta.push (root); TreeNode*p = root-Left, *CEN; while(!Sta.empty ()) { if(P) {Sta.push (P); P= P-Left ; } Else{cen=Sta.top (); Sta.pop (); Perm.push_back (CEN-val); if(CEN-Right ) {Sta.push (cen-Right ); P= CEN-RightLeft ; } } } } voidInorderc (TreeNode *root,intVal1,intVAL2)//The middle sequence traversal modifies the corresponding value { if(Root = NULL)return ; Stack<treenode *>STA; Sta.push (root); TreeNode*p = root-Left, *CEN; while(!Sta.empty ()) { if(P) {Sta.push (P); P= P-Left ; } Else{cen=Sta.top (); Sta.pop (); if(CEN-val = =val1) Cenval =Val2; Else if(CEN-val = =val2) Cenval =Val1; if(CEN-Right ) {Sta.push (cen-Right ); P= CEN-RightLeft ; } } } } voidRecovertree (TreeNode *root) { if(!root)return ; Vector<int>Perm; Inorder (root, perm); intVal1, Val2; BOOLFlag =true; for(inti =0; I < perm.size (); ++i) {if(Flag && i +1< Perm.size () && perm[i] > perm[i+1])//for the first time than after a large number{val1=Perm[i]; Flag=false; } ifI1>=0&& Perm[i] < perm[i-1])//the last number is smaller than the previous one.Val2 =Perm[i]; } inorderc (Root, Val1, val2); }};View Code
Then we think of improvements, record two nodes in a single middle-order traversal, and then exchange values.
LEETCODE[99] Recover Binary Search Tree