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