// 308ms
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 void recoverTree(TreeNode *root) { 13 // Start typing your C/C++ solution below 14 // DO NOT write int main() function 15 TreeNode *p=NULL,*q=NULL,*r,*first,*second; 16 int flag=0; 17 stack<TreeNode*> s; 18 19 r=root; 20 while(r||!s.empty()) 21 { 22 if (r) 23 { 24 s.push(r); 25 r=r->left; 26 } 27 else 28 { 29 TreeNode *top=s.top(); 30 s.pop(); 31 if(p==NULL) 32 p=top; 33 else 34 { 35 q=p; 36 p=top; 37 if(q->val>p->val) 38 { 39 if(flag==0) 40 { 41 first=q; 42 second=p; 43 flag=1; 44 } 45 else 46 { 47 second=p; 48 } 49 } 50 } 51 r=top->right; 52 53 } 54 } 55 int t=first->val; 56 first->val=second->val; 57 second->val=t; 58 } 59 };