public static void main(String[] args) { int n = 10000; if (args.length > 0) n = Integer.parseInt(args[0]); List<Integer> sorted = new ArrayList<Integer>(n); for (int i = 0; i < n; i++) sorted.add(new Integer(i)); List<Integer> shuffled = new ArrayList<Integer>(sorted); Collections.shuffle(shuffled); Queue<Integer> pq = new PriorityQueue<Integer>(n, new MyComparator()); for (Iterator<Integer> i = shuffled.iterator(); i.hasNext(); ) pq.add(i.next()); List<Integer> recons = new ArrayList<Integer>(); while (!pq.isEmpty()) recons.add(pq.remove()); if (!recons.equals(sorted)) throw new RuntimeException("Sort test failed"); recons.clear(); pq = new PriorityQueue<Integer>(shuffled); while (!pq.isEmpty()) recons.add(pq.remove()); if (!recons.equals(sorted)) throw new RuntimeException("Sort test failed"); // Remove all odd elements from queue pq = new PriorityQueue<Integer>(shuffled); for (Iterator<Integer> i = pq.iterator(); i.hasNext(); ) if ((i.next().intValue() & 1) == 1) i.remove(); recons.clear(); while (!pq.isEmpty()) recons.add(pq.remove()); for (Iterator<Integer> i = sorted.iterator(); i.hasNext(); ) if ((i.next().intValue() & 1) == 1) i.remove(); if (!recons.equals(sorted)) throw new RuntimeException("Iterator remove test failed."); }
private boolean roleSettingOperation( TestPlanEntity testPlan, Host tester, List<Engine> idleEngines, List<Engine> engineOnTester) { Queue<Engine> engineQ = new ArrayDeque<>(); engineQ.addAll(engineOnTester); boolean finished = setUpRemoteEngines(testPlan, engineQ); if (!finished) { if (engineQ.isEmpty()) { engineQ.addAll(idleEngines); finished = setUpRemoteEngines(testPlan, engineQ); if (!finished) { _logger.error( String.format( "Testplan: %d can't init. Too many engine role faults", testPlan.getId())); return true; } } else { _logger.error( String.format( "Testplan: %d can't init. Not enough available engines", testPlan.getId())); return true; } } else { if (!engineQ.isEmpty()) { List<Engine> enginesToBeKicked = engineQ.stream().collect(Collectors.toList()); _logger.warn( String.format("Host: %d has to many engines, should kickout some.", tester.getId())); if (!hostService.kickEnginesToRandomHost(enginesToBeKicked, tester)) { _logger.warn(String.format("Host: %d kick out failed. please retry", tester.getId())); return true; } } } return false; }
private boolean setUpRemoteEngines(TestPlanEntity testPlan, Queue<Engine> engineQ) { List<EngineRole> engineRoles = testPlan.getTestTenant().getEngineList(); Queue<EngineRole> engineRoleQ = new ArrayDeque<>(); engineRoleQ.addAll(engineRoles); while (!engineRoleQ.isEmpty()) { EngineRole role = engineRoleQ.remove(); if (engineQ.size() < engineRoles.size()) { _logger.error( String.format( "Testplan: %d can't init. Not enough available engines", testPlan.getId())); return true; } while (true) { Engine e = engineQ.remove(); if (engineService.setRemoteEngineRole(e, role)) { break; } if (engineQ.isEmpty()) { _logger.error( String.format( "Testplan: %d can't init. Not enough available engines", testPlan.getId())); return true; } } } return false; }
private static void levelOrderPrint(Node root) { Queue<Node> que = new LinkedList<Node>(); Node mark = new Node(0); if (root != null) { que.add(root); que.add(mark); } while (!que.isEmpty()) { Node temp = que.poll(); if (temp != mark) { System.out.print(temp.data + " "); } else { if (que.isEmpty()) { return; } que.add(mark); System.out.println(); } if (temp.left != null) { que.add(temp.left); } if (temp.right != null) { que.add(temp.right); } } }
/** 15. 第二个基本是shortest path, 给你两个node, 让你找最短路径. */ public int findShortestPath(Node departure, Node dest) { int shortestLen = 0; Queue<Node> queue = new LinkedList<Node>(); HashSet<Node> visited = new HashSet<Node>(); queue.offer(departure); visited.add(departure); queue.offer(null); while (!queue.isEmpty()) { Node curNode = queue.poll(); if (curNode == null) { shortestLen++; if (!queue.isEmpty()) { queue.offer(null); } } else { if (curNode == dest) break; for (Node n : curNode.neighbors) { if (!visited.contains(n)) { visited.add(n); queue.offer(n); } } } } return shortestLen; }
public double robinRound(int[] arrival, int[] execute, int q) { if (arrival == null || arrival.length == 0 || execute == null || execute.length == 0) { return 0.0; } int currentTime = 0; int waitingTime = 0; int nextProIndex = 0; Queue<Process> queue = new LinkedList<Process>(); while (!queue.isEmpty() || nextProIndex < arrival.length) { if (!queue.isEmpty()) { Process cur = queue.poll(); waitingTime += currentTime - cur.arri; currentTime += Math.min(cur.exe, q); for (int i = nextProIndex; i < arrival.length; i++) { if (arrival[i] <= currentTime) { queue.offer(new Process(arrival[i], execute[i])); nextProIndex++; } else { break; } } if (cur.exe > q) { queue.offer(new Process(currentTime, cur.exe - q)); } } else { queue.offer(new Process(arrival[nextProIndex], execute[nextProIndex])); currentTime += arrival[nextProIndex++]; } } return (double) waitingTime / arrival.length; }
public double shortestJobFirst(int[] arrival, int[] execute) { if (arrival == null || arrival.length == 0 || execute == null || execute.length == 0) { return 0.0; } int currentTime = 0; int waitingTime = 0; int numberOfWaiting = 0; Queue<Process> queue = new LinkedList<Process>(); while (!queue.isEmpty() || numberOfWaiting < arrival.length) { if (!queue.isEmpty()) { Process cur = queue.poll(); waitingTime += currentTime - cur.arri; currentTime += cur.exe; Vector<Process> waitingList = new Vector<Process>(); for (int i = numberOfWaiting; i < arrival.length; i++) { if (arrival[i] < currentTime) { waitingList.add(new Process(arrival[i], execute[i])); numberOfWaiting++; } else { break; } } Collections.sort(waitingList, processComparator); for (int i = 0; i < waitingList.size(); i++) { queue.offer(waitingList.get(i)); } waitingList.clear(); } else { queue.offer(new Process(arrival[numberOfWaiting], execute[numberOfWaiting])); currentTime += arrival[numberOfWaiting++]; } } return (double) waitingTime / arrival.length; }
private static List<Integer> buildSkyline(Map<Integer, List<Building>> city) { Queue<Building> heights = new PriorityQueue<Building>(); boolean[] active = new boolean[MAX_B + 1]; List<Integer> skyline = new LinkedList<Integer>(); int currHeight = 0; for (Integer p : city.keySet()) { for (Building b : city.get(p)) { if (p.intValue() == b.left) { heights.offer(b); active[b.idx] = true; } else { active[b.idx] = false; if (b.height == heights.peek().height) { while (!heights.isEmpty() && !active[heights.peek().idx]) { heights.poll(); } } } } if (heights.isEmpty()) { skyline.add(p); skyline.add(0); currHeight = 0; } else if (currHeight != heights.peek().height) { skyline.add(p); skyline.add(heights.peek().height); currHeight = heights.peek().height; } // System.out.printf("Point %d. Heights: %s; Skyline: %s\n", // p, heights, skyline); } return skyline; }
public static void bfs(int nodes[], boolean[] visited, int s, int[] max_level) { Queue<Integer> q = new LinkedList<Integer>(); q.add(s); q.add(-1); visited[s] = true; int levelNo = 2; levelNode.put(1, new ArrayList<Integer>()); levelNode.get(1).add(s); level.put(s, 1); parent.put(s, -1); while (!q.isEmpty()) { int val = (int) (q.poll()); if (val == -1) { levelNo++; if (!q.isEmpty()) q.add(-1); } else { for (int i : adjacentList.get(val)) { if (!visited[i]) { visited[i] = true; q.add(i); if (!levelNode.containsKey(levelNo)) levelNode.put(levelNo, new ArrayList<Integer>()); levelNode.get(levelNo).add(i); level.put(i, levelNo); max_level[0] = Math.max(max_level[0], levelNo); parent.put(i, val); } } } } }
public static int maxSumLevel(TreeNode root) { if (root == null) return 0; Queue<TreeNode> Q = new LinkedList<>(); TreeNode identifierNode = new TreeNode(-1); int sum = 0; int maxSum = 0; int level = 1; int maxLevel = 1; Q.add(root); Q.add(identifierNode); while (!Q.isEmpty()) { TreeNode temp = Q.remove(); if (temp == identifierNode) { if (sum > maxSum) { maxSum = sum; maxLevel = level; sum = 0; } if (!Q.isEmpty()) { Q.add(identifierNode); level++; } } else { sum += temp.val; if (temp.left != null) Q.add(temp.left); if (temp.right != null) Q.add(temp.right); } } return level; }
// ------------------- Solution 2 -------------------// // sentinel -> null (practice your coding capability) public List<List<Integer>> levelOrder3(TreeNode root) { // input validation List<List<Integer>> res = new ArrayList<List<Integer>>(); if (root == null) { return res; } // traverse level by level Queue<TreeNode> q = new LinkedList<TreeNode>(); q.add(root); q.add(null); List<Integer> item = new ArrayList<Integer>(); while (!q.isEmpty()) { // case 1: end of level reached TreeNode cur = q.poll(); if (cur == null) { res.add(new ArrayList<Integer>(item)); // attention, need to new a List item.clear(); if (!q.isEmpty()) { // add sentinel for next level: only when q is not empty!!! q.offer(null); } // case 2: in current level } else { item.add(cur.val); if (cur.left != null) { q.offer(cur.left); } if (cur.right != null) { q.offer(cur.right); } } } return res; }
/** * Finds the shortest possible path, measured in number of edges traversed, between two vertices, * a and b, in a graph, and returns this distance. The distance between a vertex and itself is * zero. Throws NoPathFoundException if there does not exist a path between a and b. * * @param graph the graph which contains vertices a and b * @param a the starting vertex contained in the graph * @param b the vertex to be traveled to (end vertex), contained in the same graph as a * @return the number of edges traversed to get from a to b along the shortest path * @throws NoPathFoundException if there does not exist a path from a to b */ public static int shortestDistance(Graph graph, Vertex a, Vertex b) throws NoPathFoundException { Queue<Vertex> nextVertexQueue = new LinkedList<Vertex>(); HashSet<Vertex> scheduledSet = new HashSet<Vertex>(); nextVertexQueue.addAll(graph.getDownstreamNeighbors(a)); scheduledSet.addAll(graph.getDownstreamNeighbors(a)); int depth = 1; while (!nextVertexQueue.isEmpty()) { Queue<Vertex> currentVertexQueue = new LinkedList<Vertex>(nextVertexQueue); nextVertexQueue = new LinkedList<>(); while (!currentVertexQueue.isEmpty()) { Vertex currentRoot = currentVertexQueue.poll(); if (currentRoot.equals(b)) return depth; else { for (Vertex each_child : graph.getDownstreamNeighbors(currentRoot)) { if (!scheduledSet.contains(each_child)) { nextVertexQueue.add(each_child); scheduledSet.add(each_child); } } } } depth++; } throw new NoPathFoundException(); }
private static void traverse(BinaryTreeNode node) { if (node == null) return; Queue<BinaryTreeNode> queue = new LinkedList<BinaryTreeNode>(); Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>(); queue.add(node); queue.add(null); while (!queue.isEmpty()) { node = queue.poll(); stack.push(node); if (node == null) { if (!queue.isEmpty()) queue.add(null); } else { if (node.getRightNode() != null) queue.add(node.getRightNode()); if (node.getLeftNode() != null) queue.add(node.getLeftNode()); } } while (!stack.isEmpty()) { BinaryTreeNode btNode = stack.pop(); if (btNode != null) { System.out.print(btNode.getData() + " "); } else { System.out.println(" "); } } }
/** @return true if there is still work to be processed. */ public boolean isBusyOld() { return !(mCreateMarkerTasks.isEmpty() && mOnScreenCreateMarkerTasks.isEmpty() && mOnScreenRemoveMarkerTasks.isEmpty() && mRemoveMarkerTasks.isEmpty() && mAnimationTasks.isEmpty()); }
public void print() { Node marker = new Node(); Node emptyNode = new Node(); Queue<Node> queue = new ArrayBlockingQueue<Node>(1000); queue.offer(root); queue.offer(marker); while (!queue.isEmpty()) { Node currentNode = queue.poll(); if (currentNode == marker && !queue.isEmpty()) { queue.offer(marker); System.out.println(""); } else { if (currentNode == emptyNode) { System.out.print(" - "); } else { if (currentNode != marker) { String print = " " + currentNode.getKey() + " "; if (currentNode.isRed()) print = " <" + currentNode.getKey() + "> "; System.out.print(print); } if (currentNode.getLeft() == null) queue.offer(emptyNode); else queue.offer(currentNode.getLeft()); if (currentNode.getRight() == null) queue.offer(emptyNode); else queue.offer(currentNode.getRight()); } } } }
// 思路,还是一样借助两个队列来进行完成 public void connect(TreeLinkNode root) { if (root == null) { return; } Queue<TreeLinkNode> q1 = new LinkedList<TreeLinkNode>(); Queue<TreeLinkNode> q2 = new LinkedList<TreeLinkNode>(); q1.add(root); root.next = null; while (!(q1.isEmpty() && q2.isEmpty())) { while (!q1.isEmpty()) { TreeLinkNode node = q1.poll(); if (node.left != null) { q2.add(node.left); } if (node.right != null) { q2.add(node.right); } } while (!q2.isEmpty()) { TreeLinkNode node = q2.poll(); if (q2.isEmpty()) { node.next = null; } else { node.next = q2.peek(); } q1.add(node); } } }
public void addItems(List<String> names, List<T> items) { if (!locationMap.isEmpty()) { throw new IllegalStateException("addItems can only be called once for any given Lattice"); } Queue<String> nameQueue = new LinkedList<String>(names); Queue<T> itemQueue = new LinkedList<T>(items); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { if (nameQueue.isEmpty() || itemQueue.isEmpty()) return; String name = nameQueue.remove(); T item = itemQueue.remove(); locationMap.put(name, new PVector(i, j, k)); contentsMap.put(name, item); } } } if (!nameQueue.isEmpty()) { log.warn( "Could not add all items to lattice of size " + size + ". Items remaining: " + nameQueue.size()); } }
@Override public synchronized int read(byte[] b, int off, int len) throws IOException { if (len == 0) { return 0; } try { while (state_ == State.OPEN && queue_.isEmpty()) { wait(); } if (state_ == State.KILLED) { throw new IOException("Stream has been closed"); } if (state_ == State.CLOSED && queue_.isEmpty()) { return -1; } if (len > queue_.size()) { len = queue_.size(); } for (int i = 0; i < len; ++i) { b[off++] = queue_.remove(); } return len; } catch (InterruptedException e) { throw new IOException("Interrupted"); } }
/** * Read input commands and execute transactions * * @throws Exception * @author Deepti Verma */ public void run() throws Exception { String line = null; // Read and execute input operations while ((line = br.readLine()) != null) { line = line.trim(); if (!(line.startsWith("\\") || line.isEmpty())) { // Ignore a line that starts with \\ then it is comment or is empty String[] operations = line.split(";"); for (int i = 0; i < operations.length; i++) { operations[i] = operations[i].trim(); doOperation(operations[i]); } } // Check for transactions waiting to be executed Queue<Transaction> tempQueue = new ArrayDeque<>(); while (!transactionWaitingList.isEmpty()) { Transaction tr = transactionWaitingList.poll(); if (tr.isWaiting && !tempQueue.contains(tr)) { if (!doOperation(tr.operationWaiting)) { anyTransactionsWaiting = true; tempQueue.add(tr); } else { tr.isWaiting = false; } } } if (!tempQueue.isEmpty()) transactionWaitingList.addAll(tempQueue); currentTimeStamp++; } bw.flush(); }
/* * Serialize uses queue implementation * Time complexity: O(h*2^(h-1)), h is height of binary tree * Extra space: O(2^(h-1)) * * @see SerializeDeserialize#serialize(TreeNode) */ public String serialize(TreeNode root) { // TODO Auto-generated method stub if (root == null) return ""; StringBuilder result = new StringBuilder("["); Queue<TreeNode> curr_lv = new LinkedList<>(); boolean finished = false; curr_lv.offer(root); while (!finished && !curr_lv.isEmpty()) { int size = curr_lv.size(); Queue<TreeNode> next_lv = new LinkedList<>(); finished = true; // System.out.println(Arrays.asList(curr_lv)); while (!curr_lv.isEmpty()) { TreeNode node = curr_lv.poll(); if (node == null) { result.append("null").append(','); continue; } result.append(String.valueOf(node.val)).append(','); if (node.left != null || node.right != null) finished = false; next_lv.offer(node.left); next_lv.offer(node.right); } // System.out.println(result+","+finished); curr_lv = next_lv; } return result.deleteCharAt(result.length() - 1).append(']').toString(); }
// Returns if the word is in the data structure. A word could // contain the dot character '.' to represent any one letter. public boolean search(String word) { Queue<TrieNode> queue = new LinkedList<TrieNode>(); queue.add(root); for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (queue.isEmpty()) return false; Queue<TrieNode> tempQueue = new LinkedList<TrieNode>(); while (!queue.isEmpty()) { TrieNode tempNode = queue.poll(); if (c == '.') { for (int j = 0; j < 26; j++) { if (tempNode.children[j] != null) tempQueue.offer(tempNode.children[j]); } } else { if (tempNode.children[c - 'a'] != null) tempQueue.add(tempNode.children[c - 'a']); } } queue = tempQueue; } boolean res = false; while (!queue.isEmpty()) { TrieNode tempNode = queue.poll(); res = res || tempNode.isWord; } return res; }
public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> results = new LinkedList<List<Integer>>(); Queue<TreeNode> currentLevel = new LinkedList<TreeNode>(); Queue<TreeNode> nextLevel = new LinkedList<TreeNode>(); if (root == null) { return results; } else { currentLevel.add(root); } List<Integer> tmp = new LinkedList<Integer>(); while (!currentLevel.isEmpty()) { TreeNode node = currentLevel.remove(); if (node != null) { tmp.add(node.val); nextLevel.add(node.left); nextLevel.add(node.right); } if (currentLevel.isEmpty()) { if (!tmp.isEmpty()) { results.add(0, tmp); } tmp = new LinkedList<Integer>(); currentLevel = nextLevel; nextLevel = new LinkedList<TreeNode>(); } } return results; }
private void moveToNextInputStream() throws IOException { if (consumeStrategy.isConsumed() && isClosed) { return; } // Throw any exception that might have occurred during previous records throwLastFailure(); // Check the isClosed flag in case we've got waken up by a close() while (!warmUpStrategy.isReady(this) || (inputStreamBuffer.isEmpty() && !isClosed)) { synchronized (consumerMonitor) { try { debug("[C] Wait for more input (is warm up ready: " + warmUpStrategy.isReady(this) + ")"); consumerMonitor.wait(1000); debug("[C] Wait for more input done."); } catch (InterruptedException e) { throw new RuntimeException(e); } if (isClosed) { break; } } } if (!inputStreamBuffer.isEmpty()) { if (currentStream != null) { currentStream.close(); } currentStream = inputStreamBuffer.poll(); } else { currentStream = null; hasFinishedRead.set(true); } synchronized (producerMonitor) { producerMonitor.notifyAll(); } debug("[C] Remaining buffers : " + inputStreamBuffer.size()); }
public void connect(TreeLinkNode root) { if (root == null) return; Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>(); Queue<Integer> depth = new LinkedList<Integer>(); depth.add(1); queue.add(root); while (!queue.isEmpty()) { TreeLinkNode parent = queue.poll(); Integer parDep = depth.poll(); if (parent.left != null) { queue.add(parent.left); depth.add(parDep + 1); } if (parent.right != null) { queue.add(parent.right); depth.add(parDep + 1); } // 还是广度搜索; if (!queue.isEmpty()) { TreeLinkNode next = queue.peek(); Integer nextDep = depth.peek(); if (nextDep != parDep) parent.next = null; else parent.next = next; } else parent.next = null; } }
// BFS public static int bfs(TreeNode root) { if (root == null) { return 0; // Edge case. } Queue<TreeNode> cur = new LinkedList<TreeNode>(), next = new LinkedList<TreeNode>(); cur.add(root); boolean oddLevel = true; // Consider root as level 1. int ret = 0; TreeNode node; while (!cur.isEmpty()) { node = cur.poll(); ret = (oddLevel) ? ret + node.val : ret - node.val; if (node.left != null) { next.add(node.left); } if (node.right != null) { next.add(node.right); } if (cur.isEmpty()) { // Swap cur and next; cur = next; next = new LinkedList<TreeNode>(); oddLevel = !oddLevel; } } return ret; }
protected void onUpdateData(int reason) { publishUpdate( new ExtensionData() .visible(true) .icon(R.drawable.ic_extension_example) .status("Rss") .expandedTitle( (feedqueue.isEmpty()) ? "Error grabbing feeds" : feedqueue.peek().getTitle()) .expandedBody( (feedqueue.isEmpty()) ? "Error grabbing feeds" : feedqueue.peek().getDescription()) .clickIntent( new Intent( Intent.ACTION_VIEW, Uri.parse( (feedqueue.isEmpty()) ? "Error grabbing feeds" : feedqueue.peek().getLink().toString())))); if ((new java.util.Date()).getTime() - lastUpdate > 3600000) updateFeeds(); else if (!feedqueue.isEmpty()) { Log.d("swiggins", "Displaying: " + feedqueue.peek().getTitle()); feedqueue.poll(); Log.d("swiggins", "Up next: " + feedqueue.peek().getTitle()); } else onInitialize(true); }
public static long[] routing(boolean[][] grid, int L, int C) { Queue<Loc> queue = new LinkedList<Loc>(); long[][] routingMap = new long[L][C]; routingMap[0][0] = 1; queue.add(new Loc(0, 0)); long level = 0; Loc endLoc = new Loc(L - 1, C - 1); while (!queue.isEmpty()) { Set<Loc> prepareSet = new HashSet<Loc>(); while (!queue.isEmpty()) { Loc poll = queue.poll(); for (int[] o : offsets) { int tx = poll.x + o[0]; int ty = poll.y + o[1]; if (0 > tx || tx >= L || 0 > ty || ty >= C || !grid[tx][ty]) continue; Loc tLoc = new Loc(tx, ty); if (routingMap[tx][ty] == 0) prepareSet.add(tLoc); if (prepareSet.contains(tLoc)) { routingMap[tx][ty] += routingMap[poll.x][poll.y]; routingMap[tx][ty] %= 1E9 + 7; } } } level++; if (prepareSet.contains(endLoc)) break; queue.addAll(prepareSet); prepareSet.clear(); } if (routingMap[L - 1][C - 1] == 0) level = -1; return new long[] {routingMap[L - 1][C - 1], level}; }
public static void lightChange(Queue<Car> q) { // if light is true, that means the green light is for N and S // This means we must change the cars wait times in E and W Queue<Car> temp = new LinkedList<Car>(); Car tc; while (!q.isEmpty()) { tc = q.remove(); temp.add(tc); } int tnum = 1; q.clear(); // System.out.println("In the light change"); while (!temp.isEmpty()) { Car tcar = temp.remove(); // System.out.println("Light Change: " + tcar.display()); if (tnum == 1) { tcar.setTotalWait(3); tcar.setWaitTime(3); q.add(tcar); } else if (tnum == 2) { tcar.setTotalWait(2); tcar.setWaitTime(2); q.add(tcar); } else { tcar.setTotalWait(1); tcar.setWaitTime(1); q.add(tcar); } tnum++; } }
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if (root == null) { return result; } Queue<TreeNode> q = new LinkedList<TreeNode>(); q.add(root); while (!q.isEmpty()) { Queue<TreeNode> tq = new LinkedList<TreeNode>(q); ArrayList<Integer> level = new ArrayList<Integer>(); q.clear(); while (!tq.isEmpty()) { TreeNode c = tq.poll(); level.add(c.val); if (c.left != null) { q.add(c.left); } if (c.right != null) { q.add(c.right); } } result.add(level); } Collections.reverse(result); return result; }
private static String printOrder(Queue<Order> priorityQueue) { StringBuilder sb = new StringBuilder(); while (!priorityQueue.isEmpty()) { sb.append(priorityQueue.poll().orderNumber); if (!priorityQueue.isEmpty()) sb.append(" "); } return sb.toString(); }