Perfect Binary Tree Specific Level Order Traversal
Given a Perfect Binary Tree like below: (click on image to get a clear view)

Print the level order of nodes in following specific manner:
1 2 3 4 7 5 6 8 15 9 14 10 13 11 12 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24
i.e. print nodes in level order but nodes should be from left and right side alternatively. Here 1st and 2nd levels are trivial. While 3rd level: 4(left), 7(right), 5(left), 6(right) are printed. While 4th level: 8(left), 15(right), 9(left), 14(right), .. are printed. While 5th level: 16(left), 31(right), 17(left), 30(right), .. are printed.
class Solution {
public void solve(Node root) {
Queue<Node> q = new LinkedList<>();
q.add(root);
while (q.size() != 0) {
int size = q.size();
LinkedList<Integer> list = new LinkedList<>();
while (size-- > 0) {
Node temp = q.poll();
list.add(temp.data);
if (temp.left != null)
q.add(temp.left);
if (temp.right != null)
q.add(temp.right);
}
int start = 0, end = list.size() - 1;
while (start <= end) {
System.out.print(list.get(start) + " ");
if (start != end)
System.out.print(list.get(end) + " ");
start++;
end--;
}
System.out.println();
}
}
}
PreviousConvert a given tree to its Sum TreeNextChange a Binary Tree so that every node stores sum of all nodes in left subtree
Last updated