while (q not empty) { int sz = q.size(); /* 将当前队列中的所有节点向四周扩散 */ for (int i = 0; i < sz; i++) { Node cur = q.poll(); /* 划重点:这里判断是否到达终点 */ if (cur is target) return step; /* 将 cur 的相邻节点加入队列 */ for (Node x : cur.adj()) if (x not in visited) { q.offer(x); visited.add(x); } } /* 划重点:更新步数在这里 */ step++; } }
public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> list = new ArrayList<>(); if(root == null) return list; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); while(!queue.isEmpty()){ int size = queue.size(); List<Integer> sublist = new ArrayList<>(); for(int i = 0; i< size; i++){ TreeNode node = queue.poll(); if(null != node){ sublist.add(node.val); queue.add(node.left); queue.add(node.right); } } if(!sublist.isEmpty()){ list.add(sublist); } } return list; }
DFS
1 2 3 4 5 6 7 8 9 10 11 12
visited = set() booleanDFS(node, visited){ visited.add(node); // process current node ... for next_node in node.children(){ if(not next_node in visited){ dfs(next_node, visited) } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* * Return true if there is a path from cur to target. */ booleanDFS(Node cur, Node target, Set<Node> visited){ returntrueif cur is target; for (next : each neighbor of cur) { if (next is not in visited) { add next to visted; returntrueifDFS(next, target, visited)== true; } } returnfalse; }