-
Notifications
You must be signed in to change notification settings - Fork 65
/
LevelOrderIterator.java
121 lines (107 loc) · 2.22 KB
/
LevelOrderIterator.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/**
* Data-Structures-In-Java
* LevelOrderIterator.java
*/
package com.deepak.data.structures.Iterators;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;
/**
* <br> Problem Statement :
*
* Implement an iterator that iterates through a binary tree in level order.
*
* </br>
*
* @author Deepak
*/
public class LevelOrderIterator<T> implements Iterator<T> {
/* Variable for next item to return */
private T nextItem;
/* Queue to hold items level by level */
private final Queue<TreeNode<T>> queue;
/**
* Constructor
*
* @param root
*/
public LevelOrderIterator(TreeNode<T> root) {
queue = new LinkedList<>();
queue.add(root);
}
/**
* Method to check if next element exists
*/
@Override
public boolean hasNext() {
/* If next item exists, return true */
if (nextItem != null) {
return true;
}
/* If queue is empty, return false */
if (queue.isEmpty()) {
return false;
}
/* Remove the node from the queue */
TreeNode<T> node = queue.remove();
/* If left or right child exists, add to the queue */
if (node.hasLeft()) {
queue.add(node.left);
}
if (node.hasRight()) {
queue.add(node.right);
}
/* Update next item and return true */
nextItem = node.item;
return true;
}
/**
* Method to find next element
*/
@Override
public T next() {
/* If there is no next element, throw exception */
if (!hasNext()) {
throw new NoSuchElementException("No Element left in collection!!");
}
/* Update item to return and next value */
T itemToReturn = nextItem;
nextItem = null;
return itemToReturn;
}
/**
* Method to remove the item
*/
@Override
public void remove() {
throw new UnsupportedOperationException("Remove not supported!");
}
/**
* TreeNode class
*
* @author Deepak
*
* @param <E>
*/
public static class TreeNode<E> {
/* Data in the node, left child and right child */
public E item;
public TreeNode<E> left;
public TreeNode<E> right;
/**
* Constructor
*
* @param item
*/
public TreeNode(E item) {
this.item = item;
}
public boolean hasLeft() {
return left != null;
}
public boolean hasRight() {
return right != null;
}
}
}