Reverse Odd Levels of Binary Tree
Given the root of a perfect binary tree, reverse the node values at each odd level of the tree.
- For example, suppose the node values at level
3are[2, 1, 3, 4, 7, 11, 29, 18], then it should become[18, 29, 11, 7, 4, 3, 1, 2].
Return the root of the reversed tree.
A binary tree is perfect if all parent nodes have two children and all leaves are on the same level.
The level of a node is the number of edges along the path between it and the root node.
Example 1
2 2
/ \ -> / \
3 5 5 3
/ \ / \ / \ / \
8 13 21 34 8 13 21 34Input
root = [2,3,5,8,13,21,34]Output
[2,5,3,8,13,21,34]The tree has only one odd level; the nodes at level 1 are 3 and 5, which are reversed to become 5 and 3.
Example 2
7 7
/ \ -> / \
13 11 11 13Input
root = [7,13,11]Output
[7,11,13]The nodes at level 1 are 13 and 11, which are reversed to become 11 and 13.
Constraints
- The number of nodes in the tree is in the range
[1, 2^14]. 0 <= Node.val <= 10^5rootis a perfect binary tree.