Advertisement
ogv

Untitled

ogv
May 28th, 2020
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  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. public void recoverTree(TreeNode root) {
  18. int[] outOfPlace = findOutOfPlace(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
  19. System.out.println(Arrays.toString(outOfPlace));
  20.  
  21. TreeNode badRoot = find(root, outOfPlace[1]);
  22. int another = replace(badRoot, outOfPlace[0]);
  23. replace(badRoot, another);
  24. }
  25.  
  26. private int[] findOutOfPlace(TreeNode node, int min, int max) {
  27. if (node == null) return null;
  28.  
  29. if (node.val < min) return new int [] { node.val, min };
  30. if (node.val > max) return new int [] { node.val, max };
  31.  
  32. int[] lResult = findOutOfPlace(node.left, min, node.val);
  33. if (lResult != null) return lResult;
  34.  
  35. return findOutOfPlace(node.right, node.val, max);
  36. }
  37.  
  38. private TreeNode find(TreeNode node, int val) {
  39. if (node == null) return null;
  40.  
  41. if (node.val == val) return node;
  42.  
  43. return find(val < node.val ? node.left: node.right, val);
  44. }
  45.  
  46. private Integer replace(TreeNode node, int val) {
  47. if (node == null) return null;
  48.  
  49. TreeNode next = val < node.val ? node.left: node.right;
  50.  
  51. if (next == null) {
  52. int oldVal = node.val;
  53. node.val = val;
  54. return oldVal;
  55. }
  56.  
  57. return replace(next, val);
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement