Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode() {}
- * TreeNode(int val) { this.val = val; }
- * TreeNode(int val, TreeNode left, TreeNode right) {
- * this.val = val;
- * this.left = left;
- * this.right = right;
- * }
- * }
- */
- class Solution {
- public void recoverTree(TreeNode root) {
- ArrayList<Integer> outOfPlace = new ArrayList<>();
- find(root, outOfPlace, Integer.MIN_VALUE, Integer.MAX_VALUE);
- if (outOfPlace.size() == 1) outOfPlace.add(root.val);
- swap(root, outOfPlace.get(0), outOfPlace.get(1));
- }
- private Integer find(TreeNode node, ArrayList<Integer> outOfPlace, int min, int max) {
- if (node == null) return null;
- if (node.val < min || node.val > max) return node.val;
- find(node.left, outOfPlace, min, node.val);
- find(node.right, outOfPlace, node.val, max);
- }
- private void swap(TreeNode node, int a, int b) {
- if (node == null) return;
- if (node.val == a) node.val = b;
- if (node.val == b) node.val = a;
- swap(node.left, a, b);
- swap(node.right, a, b);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment