leetcode - Recover Binary Search Tree
2013-12-15 21:02 张汉生 阅读(180) 评论(0) 编辑 收藏 举报
1 //比较巧妙的解决方法,copied from: 2 //http://blog.csdn.net/jellyyin/article/details/9018803 3 class Solution { 4 public: 5 void recoverTree(TreeNode *root) { 6 // Start typing your C/C++ solution below 7 // DO NOT write int main() function 8 TreeNode *n1=NULL; 9 TreeNode *n2=NULL; 10 TreeNode *prev=NULL; 11 findTwoNodes(root,n1,n2,prev); 12 13 if(n1!=NULL && n2!=NULL) 14 { 15 int tmp=n2->val; 16 n2->val=n1->val; 17 n1->val=tmp; 18 } 19 } 20 void findTwoNodes(TreeNode *root, TreeNode *&n1, TreeNode *&n2, TreeNode *&prev) 21 { 22 if(root==NULL) return; 23 24 findTwoNodes(root->left,n1,n2,prev); 25 if(prev!=NULL && prev->val > root->val) 26 { 27 n2=root; 28 if(n1==NULL) 29 { 30 n1=prev; 31 } 32 } 33 prev=root; 34 findTwoNodes(root->right,n1,n2,prev); 35 } 36 };