Recover Binary Search Tree

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:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public void recoverTree(TreeNode root) {
  12. if (root == null)
  13. return;
  14. TreeNode a = null;
  15. TreeNode b = null;
  16. TreeNode prev = null;
  17. TreeNode curr = root;
  18. Stack<TreeNode> stack = new Stack<>();
  19. while (!stack.isEmpty() || curr != null) {
  20. if (curr != null) {
  21. stack.push(curr);
  22. curr = curr.left;
  23. } else {
  24. curr = stack.pop();
  25. if (prev != null && prev.val > curr.val) {
  26. if (a == null) {
  27. a = prev;
  28. }
  29. b = curr;
  30. }
  31. prev = curr;
  32. curr = curr.right;
  33. }
  34. }
  35. // swap a and b to fix the problem
  36. if (a != null && b != null) {
  37. int tmp = a.val;
  38. a.val = b.val;
  39. b.val = tmp;
  40. }
  41. }
  42. }