99. 恢复二叉搜索树

My Solution

利用二叉树中序遍历有序的性质恢复

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. List<Integer> list = new ArrayList<>();
  18. int index = 0;
  19. public void recoverTree(TreeNode root) {
  20. visit(root);
  21. Collections.sort(list);
  22. print(root);
  23. }
  24. public void visit(TreeNode root) {
  25. if (root == null) {
  26. return;
  27. }
  28. visit(root.left);
  29. list.add(root.val);
  30. visit(root.right);
  31. }
  32. public void print(TreeNode root) {
  33. if (root == null) {
  34. return ;
  35. }
  36. print(root.left);
  37. root.val = list.get(index++);
  38. print(root.right);
  39. }
  40. }