层序遍历的写法:
void levelOrderTraverse(TreeNode* root) {
if (root == nullptr) {
return;
}
queue<TreeNode*> q;
q.push(root);
// 记录当前遍历到的层数(根节点视为第 1 层)
int depth = 1;
while (!q.empty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
TreeNode* cur = q.front();
q.pop();
// 访问 cur 节点,同时知道它所在的层数
cout << "depth = " << depth << ", val = " << cur->val << endl;
// 把 cur 的左右子节点加入队列
if (cur->left != nullptr) {
q.push(cur->left);
}
if (cur->right != nullptr) {
q.push(cur->right);
}
}
depth++;
}
}
或者把treenode替换为state{node,depth}每个树节点都维护一个自己的depth,适用于遍历图和dijkstra:
if (cur.node->left != nullptr) {
q.push(State(cur.node->left, cur.depth + 1));
}
BFS常用来寻找最短路径,dfs用来寻找所有路径
浙公网安备 33010602011771号