forked from ppsirker/dsalgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoveDuplicateBST.java
151 lines (133 loc) · 2.43 KB
/
RemoveDuplicateBST.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
/*
For problem and solution description please visit the link below
http://www.dsalgo.com/2013/03/remove-duplicate-infinite-integer.html
*/
package com.dsalgo;
import java.util.Iterator;
public class RemoveDuplicateBST
{
public static void main(String[] args)
{
System.out.println("Input\tOutput");
Iterator<Integer> inputIterator = new InputIterator(30);
Iterator<Integer> outputIterator = new OutputIterator(inputIterator);
while (outputIterator.hasNext())
{
System.out.println("\t<<" + outputIterator.next());
}
}
private static class InputIterator implements Iterator<Integer>
{
int count;
public InputIterator(int count)
{
this.count = count;
}
@Override
public boolean hasNext()
{
return count != 0;
}
@Override
public Integer next()
{
int input = (int) (Math.random() * 30);
System.out.println(">>" + input);
count--;
return input;
}
@Override
public void remove()
{
}
}
private static class OutputIterator implements Iterator<Integer>
{
Iterator<Integer> inputIterator;
Integer nextElement;
Node root;
public OutputIterator(Iterator<Integer> inputIterator)
{
this.inputIterator = inputIterator;
if (inputIterator.hasNext())
{
nextElement = inputIterator.next();
if (nextElement != null)
add(nextElement);
}
}
private boolean add(int value)
{
return add(root, value);
}
private boolean add(Node current, int value)
{
Node node = new Node(value);
if (current == null)
{
root = node;
return true;
}
if (current.value == value)
{
return false;
}
if (current.value > value)
{
if (current.left == null)
{
current.left = node;
return true;
} else
{
return add(current.left, value);
}
} else
{
if (current.right == null)
{
current.right = node;
return true;
} else
{
return add(current.right, value);
}
}
}
@Override
public boolean hasNext()
{
return nextElement != null;
}
@Override
public Integer next()
{
int output = nextElement;
nextElement = null;
while (inputIterator.hasNext())
{
int input = inputIterator.next();
if (add(input))
{
nextElement = input;
break;
}
}
return output;
}
@Override
public void remove()
{
}
}
private static class Node
{
int value;
Node left;
Node right;
public Node(int value)
{
this.value = value;
}
}
}