Created
October 25, 2015 19:41
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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