// --------------------------------
// 1st level order: store values
// --------------------------------
while (!curr.isEmpty()) {
TreeNode node = curr.pollLast();
list.add(node.val);
if (level % 2 == 0) {
if (node.left != null) {
next.add(node.left);
}
if (node.right != null) {
next.add(node.right);
}
} else {
if (node.right != null) {
next.add(node.right);
}
if (node.left != null) {
next.add(node.left);
}
}
if (curr.isEmpty()) {
curr = next;
next = new ArrayDeque<TreeNode>();
level++;
}
}
// --------------------------------
// 2nd level order: update values
// --------------------------------
curr = new ArrayDeque<TreeNode>();
next = new ArrayDeque<TreeNode>();
curr.add(root);
int index = 0;
while (!curr.isEmpty()) {
TreeNode node = curr.pollFirst();
// update the value
node.val = list.get(index++);
if (node.left != null) {
next.add(node.left);