树的层次遍历(102) 最小基因变化(433)括号生成(22)在每个树行中找最大值(515)
1. DFS
// 使用递归public void dfs(Node node) {if (vistied.contains(node)) {return;}visited.add(node);//dfs(node.left);dfs(node.right);}// 使用栈public void dfs(Node self, Node tree) {if (tree.root == null) {return;}Set<Node> visited = new HashSet<>();Stack<Node> stack = new Stack<>();while (!stack.isEmpty()) {Node node = stack.pop();visited.add(node);process(node);nodes = getRelatedNodes(node);stack.push(nodes);// ....}}
1.1
2. BFS
public void bfs(Node node) {Queue<Node> queue = new LinkedList<>();queue.add(node);while (!queue.isEmpty()) {Node temp = queue.poll();// handle nodeprocess(temp);// nextList<Node> relatedNodes = getRelatedNodes(temp);queue.addAll(relatedNodes);}}
