Instructions
You are given the root of a binary tree that was a valid binary search tree (BST): for every node, all values in its left subtree are smaller than its value, and all values in its right subtree are larger. All values are different.
Then the values of exactly two nodes were swapped by mistake, so the tree is no longer a valid BST.
Repair the tree: swap those two values back. Do not change the shape of the tree, do not add or remove nodes, and do not build a new tree. Change the val fields of the given nodes in place. Your function does not need to return anything — the judge reads the tree after your function ends.
How the input is shown
The tree is written in level order: the values row by row, from left to right, with null where a child is missing. For example, [2, 1, 3] is the root 2 with left child 1 and right child 3. Your function gets the TreeNode root, with fields val, left and right. The expected output is the repaired tree, in the same notation.
Hint
Visit the nodes in order (left subtree, node, right subtree). In a valid BST the values come out strictly increasing. Look for the places where a value is bigger than the next one. There are one or two such places, and they tell you which two nodes to swap.
Examples
Example 1
- Input:
- [8,12,3,1,5,10,14]
- Output:
- [8,3,12,1,5,10,14]
In order, the values are 1, 12, 5, 8, 10, 3, 14. The first drop is 12 > 5 and the last drop is 10 > 3, so 12 and 3 were swapped. After swapping them back the in-order values are 1, 3, 5, 8, 10, 12, 14.
Example 2
- Input:
- [15,10,30,null,20]
- Output:
- [20,10,30,null,15]
In order, the values are 10, 20, 15, 30. There is only one drop (20 > 15), so the two swapped values were next to each other in sorted order: 20 and 15. The root goes back to 20 and the right child of 10 goes back to 15.
Example 3
- Input:
- [-7,-4]
- Output:
- [-4,-7]
The root -7 has the left child -4, but a left child must be smaller than its parent. In order the values are -4, -7, so these two were swapped. After the repair the root is -4 and its left child is -7.
Constraints
- The tree has between
2and34nodes. -100 <= Node.val <= 100, and all values are different.- Exactly two values are out of place.
3 examples run when you press Run. Submit checks every hidden test too.
- Input:
- [8,12,3,1,5,10,14]
- Expected:
- [8,3,12,1,5,10,14]
- Input:
- [15,10,30,null,20]
- Expected:
- [20,10,30,null,15]
- Input:
- [-7,-4]
- Expected:
- [-4,-7]
Run checks your code against the 3 examples. Submit checks it against all 113 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.