Created
September 2, 2013 19:28
-
-
Save charlespunk/6416453 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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? |
This file contains hidden or 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 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