1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
class Solution { public void recoverTree(TreeNode root) { List<TreeNode> list = new ArrayList<>(); inOrder(root, list); TreeNode x = null, y = null; for (int i = 0; i < list.size() - 1; ++i) { if (list.get(i).val > list.get(i + 1).val) { y = list.get(i + 1); if (x == null) { x = list.get(i); } } } if (x != null && y != null) { int temp = x.val; x.val = y.val; y.val = temp; } }
private void inOrder(TreeNode root, List<TreeNode> list) { if (root == null) return; inOrder(root.left, list); list.add(root); inOrder(root.right, list); } }
|