Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created September 2, 2013 19:28
Show Gist options
  • Save charlespunk/6416453 to your computer and use it in GitHub Desktop.
Save charlespunk/6416453 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.
Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void recoverTree(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode first = null;
TreeNode second = null;
TreeNode last = null;
TreeNode run = root;
while(run != null){
stack.add(run);
run = run.left;
}
while(!stack.isEmpty()){
run = stack.pop();
if(last == null) last = run;
else if(run.val < last.val){
if(first == null){
first = last;
second = run;
}
else second = run;
}
last = run;
run = run.right;
while(run != null){
stack.add(run);
run = run.left;
}
}
int swap = first.val;
first.val = second.val;
second.val = swap;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment