题目
按层遍历一棵多叉树,输出层号和节点
代码
#include <iostream>
#include <vector>
#include <memory>
#include <queue>
class TreeNode
{
public:
TreeNode(int num) : num_(num) {};
TreeNode(const TreeNode& rhs) = default;
~TreeNode() = default;
int getNum() const { return num_; }
void addChild(std::shared_ptr<TreeNode>& child) { children.push_back(child); }
void addChild(std::shared_ptr<TreeNode>&& child) { children.push_back(child); }
auto getChild() const { return children; }
private:
int num_;
std::vector<std::shared_ptr<TreeNode>> children;
};
void layer(std::shared_ptr<TreeNode>& root)
{
typedef std::pair<int, std::shared_ptr<TreeNode>> PIT;
std::queue<PIT> qe;
qe.push({1, root});
while (qe.size())
{
auto ele = qe.front();
qe.pop();
std::cout << ele.first << ' ' << ele.second->getNum() << '\n';
for (auto &cld : ele.second->getChild())
{
qe.push({ele.first + 1, cld});
}
}
}
int main()
{
auto root = std::make_shared<TreeNode>(1);
root->addChild(std::make_shared<TreeNode>(2));
root->addChild(std::make_shared<TreeNode>(3));
root->addChild(std::make_shared<TreeNode>(4));
layer(root);
return 0;
}