通过万岁!!!
java代码
class Solution {
public TreeNode reverseOddLevels(TreeNode root) {
if (root == null || root.left == null) {
return root;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int r;
int l;
double level = 0;
while (queue.size() != 0) {
TreeNode remove = queue.remove();
if (remove.left != null) {
queue.add(remove.left);
}
if (remove.right != null) {
queue.add(remove.right);
}
r = queue.size() - 1;
l = 0;
double newLevel = Math.log(r + 1) / Math.log(2);
if (newLevel < level) {
continue;
} else {
level = newLevel;
}
// 如果是奇数层,则就需要进行交换了
if (newLevel % 2 == 1) {
List<TreeNode> transList = new ArrayList<>(r);
for (TreeNode treeNode : queue) {
transList.add(treeNode);
}
while (r > l) {
int temp = transList.get(r).val;
transList.get(r).val = transList.get(l).val;
transList.get(l).val = temp;
l++;
r--;
}
}
}
return root;
}
}