ogv

Untitled

ogv
May 28th, 2020
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 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. ArrayList<Integer> outOfPlace = new ArrayList<>();
  19.  
  20. find(root, outOfPlace, Integer.MIN_VALUE, Integer.MAX_VALUE);
  21. if (outOfPlace.size() == 1) outOfPlace.add(root.val);
  22.  
  23. swap(root, outOfPlace.get(0), outOfPlace.get(1));
  24. }
  25.  
  26. private Integer find(TreeNode node, ArrayList<Integer> outOfPlace, int min, int max) {
  27. if (node == null) return null;
  28.  
  29. if (node.val < min || node.val > max) return node.val;
  30.  
  31. find(node.left, outOfPlace, min, node.val);
  32. find(node.right, outOfPlace, node.val, max);
  33. }
  34.  
  35. private void swap(TreeNode node, int a, int b) {
  36. if (node == null) return;
  37.  
  38. if (node.val == a) node.val = b;
  39. if (node.val == b) node.val = a;
  40.  
  41. swap(node.left, a, b);
  42. swap(node.right, a, b);
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment