以下是使用 C++ 实现树节点的层次遍历方法的示例代码:
#include <iostream>
#include <queue>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
void levelOrder(TreeNode* root) {
if (root == nullptr) {
return;
}
std::queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode* node = q.front();
q.pop();
std::cout << node->val << " ";
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
}
}
}
int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
std::cout << "Level order traversal: ";
levelOrder(root);
return 0;
}
在上面的代码中,我们定义了一个树节点的结构体 TreeNode
,并实现了层次遍历方法 levelOrder
。在 main
函数中,我们创建了一棵树并调用 levelOrder
方法进行层次遍历。运行结果将输出树节点的值的层次遍历顺序。