You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
visited = set()
def dfs(node, visited):
if node in visited: #termintor
# 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)
DFS 代码 - 非递归写法
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 = grenerate_related_nodes(node)
statck.push(nodes)
#other processing work
#...
BFS 广度优先遍历 - 用队列
BFS 代码结构
function BFS(graph, start, end) {
let queue = []
queue.append([start])
visited.add(start)
while (queue.length) {
let node = queue.shift();
visited.add(node);
process(node)
node = generate_related_nodes(node)
queue.push(nodes)
// other processing work
}
}
let left = 0, right = array.length - 1;
while (left <= right) {
let mid = (left + right) / 2;
if (array[mid] === target) {
//find the target
//break or return result
} else if (array[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}