DFS
递归写法
def dfs(node, visited):
if node in visited: # terminator
# already visited
return
visited.add(node)
# process current node here.
...
for next_node in node.children():
if not next_node in visited:
dfs(next_node, visited)
非递归写法
def DFS(self, tree):
def DFS(self, tree):
if tree.root is None:
return []
visited, stack = [], [tree.root]
while stack:
node = stack.pop()
visited.add(node)
process (node)
nodes = generate_related_nodes(node)
stack.push(nodes)
# other processing work
...
BFS
const bfs = (root) => {
let result = [], queue = [root]
while (queue.length > 0) {
let level = [], n = queue.length
for (let i = 0; i < n; i++) {
let node = queue.pop()
level.push(node.val)
if (node.left) queue.unshift(node.left)
if (node.right) queue.unshift(node.right)
}
result.push(level)
}
return result
};