import java.util.Random;

class forReturn {
  public Integer data;
}

class Node {
  private Integer data;
  private Node left;
  private Node right;
  private Node(Integer data, Node left, Node right) {
    this.data = data;
    this.left = left;
    this.right = right;
  }
  public static Node pushNode(Node root, Integer data) {
    if (root == null) {
      return new Node(data, null, null);
    } 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, forReturn Data) {
    if (root == null)
      return null;
    if (root.left != null) {
      root.left = popNode(root.left, Data);
      return root;
    }
    Data.data = root.data;
    return root.right;
  }
}

class Main {
  final static int N = 50;
  final static int MAX = 10000;
  public static void main(String[] args) {
    Random random = new Random();
    Node root = null;
    for (int i = 0; i < N; i++) {
      Integer Data = new Integer(random.nextInt(MAX));
      root = Node.pushNode(root, Data);
      System.out.println(Data + "," + root);
    }
    System.out.println();
    do {
      forReturn Data;
      root = Node.popNode(root, Data = new forReturn());
      System.out.println(Data.data);      
    } while (root != null);
  }
}
/* end */
