Problem:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
Solution:
/**
* Definition for a binary tree node.
* 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 *cur_min = new TreeNode(INT_MIN), *one = NULL, *sec = NULL;
check(root, cur_min, one, sec);
if (one && sec) {
int tmp = one -> val;
one -> val = sec -> val;
sec -> val = tmp;
}
return;
}
void check(TreeNode *root, TreeNode *&cur_min, TreeNode *&one, TreeNode *&sec) {
if (!root) {
return;
}
check(root -> left, cur_min, one, sec);
if (cur_min -> val >= root -> val) {
if (one == NULL) {
one = cur_min;
}
sec = root;
}
cur_min = root;
check(root -> right, cur_min, one, sec);
return;
}
};
Two elements of a binary search tree (BST) are 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?
Solution:
/**
* Definition for a binary tree node.
* 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 *cur_min = new TreeNode(INT_MIN), *one = NULL, *sec = NULL;
check(root, cur_min, one, sec);
if (one && sec) {
int tmp = one -> val;
one -> val = sec -> val;
sec -> val = tmp;
}
return;
}
void check(TreeNode *root, TreeNode *&cur_min, TreeNode *&one, TreeNode *&sec) {
if (!root) {
return;
}
check(root -> left, cur_min, one, sec);
if (cur_min -> val >= root -> val) {
if (one == NULL) {
one = cur_min;
}
sec = root;
}
cur_min = root;
check(root -> right, cur_min, one, sec);
return;
}
};
No comments:
Post a Comment