Reverse Odd Levels of Binary Tree
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var reverseOddLevels = function (root) {
let queue = [root];
let level = 0;
let levelValues = [];
while (queue.length) {
const next = [];
levelValues = [];
for (let i = 0; i < queue.length; i++) {
const node = queue[i];
levelValues.push(node.val);
if (node.left) {
next.push(node.left);
}
if (node.right) {
next.push(node.right);
}
}
if (level % 2) {
levelValues = levelValues.reverse();
for (let i = 0; i < levelValues.length; i++) {
queue[i].val = levelValues[i];
}
}
queue = next;
level++;
}
return root;
};
Top comments (0)