¿Qué estoy haciendo mal con el comparador de Java 8 PriorityQueue?

buscador:

Estoy tratando de resolver este ejercicio y aquí está mi solución. Básicamente tiene un mapa del árbol para asignar los nodos en el desplazamiento a una tecla de la misma Veritical. Y utiliza una cola de prioridad a los lazos de división cuando hay varias teclas al mismo (nivel horizontal) usando el valor en el nodo.

public List<List<Integer>> verticalTraversal(TreeNode root) {
    Map<Integer, PriorityQueue<Node>> map = new TreeMap<>();
    List<List<Integer>> out = new ArrayList<>();
    if(root == null)
        return out;
    Queue<Node> q = new LinkedList<>();
    Node r = new Node(root, 0, 0);
    q.add(r);
    while(!q.isEmpty()) {
        Node curr = q.remove();
        int x = curr.x;
        int y = curr.y;
        PriorityQueue<Node> pq = map.getOrDefault(y, new PriorityQueue<Node>((a,b) ->(a.x == b.x? a.t.val - b.t.val: a.x - b.x)));
        pq.add(curr);
        map.put(y,pq);
        if(curr.t.left!=null){
            Node left = new Node(curr.t.left, x+1, y-1);
            q.add(left);
        }
        if(curr.t.right!=null){
            Node right = new Node(curr.t.right, x+1, y + 1);
            q.add(right);
        }
    }
for (Map.Entry<Integer, PriorityQueue<Node>> entry : map.entrySet()){
   PriorityQueue<Node> pq = entry.getValue();
    List<Integer> vals = new ArrayList<>();
   for (Node pqNode: pq){
       vals.add(pqNode.t.val);                       

   }
out.add(new ArrayList<Integer>(vals));

}
return out;
}




class Node {
    TreeNode t;
    int y;
    int x;
    Node(TreeNode t, int x, int y) {
        this.t = t;
        this.x = x;
        this.y = y; 
    }
}

}

Y para ser claro aquí es donde creo que el problema es

  PriorityQueue<Node> pq = map.getOrDefault(y, new PriorityQueue<Node>((a,b) ->(a.x == b.x? a.t.val - b.t.val: a.x - b.x)));

Me da la orden de esperar cuando a.xisnt igual a b.xpero no se parece ir por el valcuando son iguales.

Aquí está el caso de prueba no introducir descripción de la imagen aquíreal: [ [7,9] , [5,6], [0,2,4], [1,3], [8]] esperados: [[ 9,7] , [5, 6], [0,2,4], [1,3], [8]]

Thomas Solicitante:

Lo que su mal proceder es que iterar sobre los elementos de la cola de prioridad en lugar de la votación misma.

La documentación de PriorityQueue # iterador () establece claramente:

Devuelve un iterador sobre los elementos de esta cola. El iterador no devuelve los elementos en un orden particular.

En lugar de escribir

for (Node pqNode: pq){
    vals.add(pqNode.t.val);                       
}

Deberías usar:

Node pqNode;
while ((pqNode = pq.poll()) != null) {
    vals.add(pqNode.t.val);                       
}

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=180341&siteId=1
Recomendado
Clasificación