Skip to content

Instantly share code, notes, and snippets.

@sitano
Created October 25, 2015 19:41
Show Gist options
  • Save sitano/290e012c915be0d0039e to your computer and use it in GitHub Desktop.
Save sitano/290e012c915be0d0039e to your computer and use it in GitHub Desktop.
Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure.
/**
* 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 {
TreeNode* fst;
TreeNode* sec;
public:
void recoverTree(TreeNode* root) {
dfs(root, NULL);
int tmp = fst->val;
fst->val = sec->val;
sec->val = tmp;
}
TreeNode *dfs(TreeNode *root, TreeNode *last) {
if (root->left != NULL) {
last = dfs(root->left, last);
}
if (last != NULL && last->val > root->val) {
if (!fst) {
fst = last;
sec = root;
} else {
sec = root;
return NULL;
}
}
if (root->right != NULL) {
return dfs(root->right, root);
}
return root;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment