bfs
建立数组队列以保存节点
left指向第一个元素(及前面的元素已经被pop),right指向最后一个元素的右边(及right为下一个入队列的位置)
将根放入数组,left = 0, right = 1
while (left < right){
取left指向的结点,并pop当前节点 (left++)
将该结点的左右结点加入数组队列
}
void *mybfs(struct Node *root) {
if (!root) {
return NULL;
}
struct Node *q[LEN];
int left = 0, right = 0;
q[right++] = root;
while (left < right) {
struct Node *new = q[left++];//you can do anything with this node
if (new->left) {
q[right++] = new->left;
}
if (new->right) {
q[right++] = new->right;
}
}
}
dfs
void dfs(struct Node *root, struct result){
//stop
if (root == NULL){
//save your result
return;
}
//modify your result
dfs(root->left,result);
dfs(root->right,result);
}
int main(){
//init
dfs(root,result);
}
有个有趣的设计题:leetcode341
本文介绍了两种重要的图遍历算法——广度优先搜索(BFS)和深度优先搜索(DFS),并给出了具体的实现代码。BFS使用队列来保存待访问的节点,而DFS则递归地访问节点。这两种算法在解决图论问题中非常有用。
806

被折叠的 条评论
为什么被折叠?



