Esempio n. 1
0
  void mixLists(
      LinkedList<Integer> left,
      LinkedList<Integer> right,
      ArrayList<LinkedList<Integer>> mix,
      LinkedList<Integer> before) {
    if (before.isEmpty() || right.isEmpty()) {
      LinkedList<Integer> l = new LinkedList<>();
      l = (LinkedList<Integer>) before.clone();
      l.addAll(left);
      l.addAll(right);
      mix.add(l);
      return;
    }
    int hl = left.removeFirst();
    before.addLast(hl);
    mixLists(left, right, mix, before);
    before.removeLast();
    left.addFirst(hl);

    int hr = right.removeFirst();
    before.addLast(hr);
    mixLists(left, right, mix, before);
    before.removeLast();
    right.addFirst(hr);
  }
Esempio n. 2
0
  ArrayList<LinkedList<Integer>> bstSequences(TN nd) {
    ArrayList<LinkedList<Integer>> seq = new ArrayList<>();
    if (nd == null) {
      seq.add(new LinkedList<Integer>());
      return seq;
    }

    LinkedList<Integer> before = new LinkedList<>();
    before.add(nd.val);

    ArrayList<LinkedList<Integer>> left_seq = bstSequences(nd.left);
    ArrayList<LinkedList<Integer>> right_seq = bstSequences(nd.right);

    for (LinkedList<Integer> left : left_seq) {
      for (LinkedList<Integer> right : right_seq) {
        ArrayList<LinkedList<Integer>> mix = new ArrayList<>();
        mixLists(left, right, mix, before);
        seq.addAll(mix);
      }
    }
    return seq;
  }