1669. Swap at Every Kth Floor
A building is described by a binary tree root: the root is the first floor, its children form the second floor, and so on. A mirror-maker works through the building and, on every floor whose number is a multiple of k, swaps the left and right child of every room (node) on that floor, carrying whole subtrees along with the children.
Modify the tree in place; nothing is returned, and the root node stays the same object. Floors are numbered from 1. If k is larger than the height nothing changes, and swapping a floor does not shift which nodes belong to deeper floors. Aim for O(n) time and O(w) space, where w is the widest floor.
Example 1
- Input:
- root = [1,2,3,4,5,6,7], k = 2
- Output:
- [1,2,3,5,4,7,6]
- Explanation:
After the swaps the tree reads [1, 2, 3, 5, 4, 7, 6].
Example 2
- Input:
- root = [1,2,null,3,null,4], k = 3
- Output:
- [1,2,null,3,null,null,4]
- Explanation:
After the swaps the tree reads [1, 2, null, 3, null, null, 4].
Constraints
1 ≤ nodes ≤ 500; 1 ≤ k ≤ 500; -1000 ≤ Node.val ≤ 1000
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Graded
- Your answer is read from
rootafter your method returns. - Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n)
- Space
- O(w)