树的深度与广度优先搜索(伪代码)
深度优先搜索
public void depthFirstSearch() { Stack<Map<String, Object>> nodeStack = new Stack<Map<String, Object>>(); Map<String, Object> node = new HashMap<String, Object>(); /** * 第一个节点放入 */ nodeStack.add(node); while (!nodeStack.isEmpty()) { node = nodeStack.pop(); log.info(node); List<Map<String, Object>> list = getChildren(node); if (!CollectionUtil.isBlank(list)) { for (Map<String, Object> child : list) { nodeStack.add(child); } } } }
广度优先搜索
public void breadthFirstSearch() { ArrayDeque<Map<String, Object>> nodeDeque = new ArrayDeque<Map<String, Object>>(); Map<String, Object> node = new HashMap<String, Object>(); /** * 第一个节点放入 */ nodeDeque.add(node); while (!nodeDeque.isEmpty()) { node = nodeDeque.pop(); log.info(node); List<Map<String, Object>> list = getChildren(node); if (!CollectionUtil.isBlank(list)) { for (Map<String, Object> child : list) { nodeDeque.add(child); } } } }