树的分层遍历
是的,这个使用BFS可以很简洁地实现。不过编程之美3.10节有两个扩展问题。对于第二个问题,用BFS就不那么简便了,相反递归在这里更合适。另一方面,对于初始问题,不一定要使用queue,虽然空间上略微浪费一些(最大为其两倍),但实现代码可以同第二个扩展问题有部分共享。
下面的代码,注意swap的使用。初看以为这里会很浪费时间,实际上STL的swap实现是O(1)的。
另,关于第二个扩展问题,可以联系到下面的题目:
struct Node {
int v;
Node *left, *right;
};
void print(ostream& os, const vector<Node*>& nodes) {
for (size_t i = 0; i < nodes.size(); ++i) {
if (i) os<<' ';
os<<nodes[i]->v;
}
cout<<'\n';
}
void subtrees(const vector<Node*> nodes, vector<Node*>& subs) {
for (size_t i = 0; i < nodes.size(); ++i) {
Node* node = nodes[i];
if (node->left) subs.push_back(node->left);
if (node->right) subs.push_back(node->right);
}
}
void printTrees(ostream& os, vector<Node*> nodes) {
if (!nodes.size()) return;
vector<Node*> subs;
while (nodes.size()) {
print(os, nodes);subs.clear();
subtrees(nodes, subs);
swap(nodes, subs);
}
}
void printTrees2(ostream& os, const vector<Node*>& nodes) {
if (!nodes.size()) return;
vector<Node*> subs;
subtrees(nodes, subs);
printTrees(os, subs);
print(os, nodes);}
void printTree(ostream& os, Node* root) {
printTrees(os, vector<Node*>(1, root));
}