/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void recoverTree(TreeNode *root) { TreeNode * n1 = NULL; TreeNode * n2 = NULL; TreeNode * prev = NULL; recoverTree(root, n1, n2, prev); if(n1 && n2) { int temp = n1->val; n1->val = n2->val; n2->val = temp; } } void recoverTree(TreeNode * root, TreeNode *& n1, TreeNode *& n2, TreeNode *& prev) { if(!root) { return; } recoverTree(root->left, n1, n2, prev ); if(prev && prev->val > root->val) { n2 = root; if(!n1) { n1 = prev; } } prev = root; recoverTree(root->right, n1, n2, prev ); } };
6/08/2014
Leetcode -- Recover Binary Search Tree
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment