Heap<Node> (HeapNode<Node> node) { int pos = mySize + 1; int pow = 1; while (pos >= pow << 2) { pow <<= 1; } HeapNode<Node> newRoot = myRoot.copy(); HeapNode<Node> place = newRoot; List<HeapNode<Node>> parents = new ArrayList<>(); while (true) { parents.add(place); final int ind = (pos & pow) != 0 ? 1 : 0; if (pow == 1) { place.myChildren[ind] = node; break; } HeapNode<Node> copy = place.myChildren[ind].copy(); place.myChildren[ind] = copy; place = copy; pow >>= 1; } for (int i = parents.size() - 1; i >= 0; i--) { HeapNode<Node> parent = parents.get(i); if (parent.myEdge.getDelta() < node.myEdge.getDelta()) { break; } final GraphEdge<Node> t = parent.myEdge; parent.myEdge = node.myEdge; node.myEdge = t; final HeapNode<Node> t2 = parent.myChildren[2]; parent.myChildren[2] = node.myChildren[2]; node.myChildren[2] = t2; node = parent; } return new Heap<>(mySize + 1, newRoot); }