import java.util.Random;
class Indirect {
int data;
boolean flag;
}
class Node {
private int data;
private Node left;
private Node right;
private Node(int data) {
this.data = data;
this.left = this.right = null;
}
public static Node pushNode(Node root, int data) {
if (root == null) {
return new Node(data);
} else if (data < root.data) {
root.left = pushNode(root.left, data);
return root;
} else {
root.right = pushNode(root.right, data);
return root;
}
}
public static Node popNode(Node root, Indirect idata) {
if (root == null) {
idata.flag = false;
return null;
}
if (root.left != null) {
root.left = popNode(root.left, idata);
return root;
}
idata.data = root.data;
idata.flag = true;
return root.right;
}
}
class BinTree {
private Node root;
BinTree() { root = null; }
void pushNode(int data) { root = Node.pushNode(root, data); }
Indirect popNode() {
Indirect idata;
root = Node.popNode(root, idata = new Indirect());
if (idata.flag == false)
return null;
return idata;
}
}
class Main {
final static int N = 10;
final static int MAX = 1000;
public static void main
(String[] args
) { BinTree root = new BinTree();
int data;
for (int i = 0; i < N; i++) {
data = random.nextInt(MAX);
root.pushNode(data);
}
Indirect idata;
while ((idata = root.popNode()) != null) {
int rdata = idata.data;
}
}
}
/* end */
aW1wb3J0IGphdmEudXRpbC5SYW5kb207CgpjbGFzcyBJbmRpcmVjdCB7CiAgaW50IGRhdGE7CiAgYm9vbGVhbiBmbGFnOwp9CgpjbGFzcyBOb2RlIHsKICBwcml2YXRlIGludCBkYXRhOwogIHByaXZhdGUgTm9kZSBsZWZ0OwogIHByaXZhdGUgTm9kZSByaWdodDsKICBwcml2YXRlIE5vZGUoaW50IGRhdGEpIHsKICAgIHRoaXMuZGF0YSA9IGRhdGE7CiAgICB0aGlzLmxlZnQgPSB0aGlzLnJpZ2h0ID0gbnVsbDsKICB9CiAgcHVibGljIHN0YXRpYyBOb2RlIHB1c2hOb2RlKE5vZGUgcm9vdCwgaW50IGRhdGEpIHsKICAgIGlmIChyb290ID09IG51bGwpIHsKICAgICAgcmV0dXJuIG5ldyBOb2RlKGRhdGEpOwogICAgfSBlbHNlIGlmIChkYXRhIDwgcm9vdC5kYXRhKSB7CiAgICAgIHJvb3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