Implementing heaps

Date: April 8, 2023

Topic: Heap & Graph Search Algorithms

Recall

Heap intro

Question

Q1 Find smallest kth elements form an unsorted array(size n)

Representation of graph

图里常见的search

经典例题BFS-1:Level order

get Keys in binary tree layer by layer

Notes

3531CF8B-DF3E-429B-9344-7FD3F0AAD623.png

Breadth First Search BFS -1


public class solution {
	public List<List<Integer>> LayerByLayer(TreeNode root) {
		List<List<Integer>> list = new ArrayList<>();
		if (root == null) {
			return list;
		}
		//用一个queue来装整棵树
		Queue<TreeNode> queue = new LinkedList<>();
		queue.offer(root);
		while (!queue.isEmpty()) {
			List<Integer> curLayer = new ArrayList<>();
			int size = queue.size;
			for (int i = 0; i < size; i++) {
				TreeNode cur = queue.poll();
				curLayer.add(cur.key);
				if (cur.left != null) {
					queue.offer(cur.left);
				}
				if (cur.right != null) {
					queue.offer(cur.right);
				}
			}
			list.add(curLayer);
		}
		return list;
}
TC: O(n)
SC: O(n)

Best First Search (BFS - 2)

<aside> 💡 dijkstra’s algorithm 的重要性质

<aside> 📌 SUMMARY:

</aside>


Date: April 8, 2023

Topic: Heap in Java(PriorityQueue)

Recall

K Smallest in unsorted Array

Notes

两种方式provide a comparator class or set class with natural ordering

public int compareTo(Integer anotherInt)
return:
- 0,两者相等
- -1, this.Integer < anotherInt
- 1, this.Integer > anotherInt

eg. Integer a = new Integer(10);
    Integer b = new Integer(20);
Ststem.out.println(a.compareTo(b));  -1;

Declaration: PriorityQueue<MyInteger> pq = new PriortyQueue<>( );

Declaration: PriorityQueue<MyInteger> pq = new PriortyQueue<>( );

<aside> 📌 SUMMARY:

</aside>


Date: April 9, 2023

Topic: Practice 10 Implementing Heaps

<aside> 📌 SUMMARY:

</aside>