-
Notifications
You must be signed in to change notification settings - Fork 5
/
ReverseLevelOrder.java
34 lines (33 loc) · 1.16 KB
/
ReverseLevelOrder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*https://practice.geeksforgeeks.org/problems/reverse-level-order-traversal/1*/
class Tree
{
public ArrayList<Integer> reverseLevelOrder(Node node)
{
// code here
ArrayList<ArrayList<Integer>> levelOrder = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> result = new ArrayList<Integer>(), currList = new ArrayList<Integer>();
Queue<Node> queue = new LinkedList<Node>();
int len = -1, i = -1;
Node currNode = null;
queue.add(node);
while (!queue.isEmpty())
{
len = queue.size();
currList = new ArrayList<Integer>();
for (i = 0; i < len; ++i)
{
currNode = queue.poll();
currList.add(currNode.data);
if (currNode.left != null) queue.add(currNode.left);
if (currNode.right != null) queue.add(currNode.right);
}
levelOrder.add(currList);
}
for (i = levelOrder.size()-1; i >= 0; --i)
{
currList = (ArrayList)levelOrder.get(i);
for (Integer elem : currList) result.add(elem);
}
return result;
}
}