以下是使用 C++ 實現(xiàn)樹節(jié)點的層次遍歷方法的示例代碼:
#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;
}
在上面的代碼中,我們定義了一個樹節(jié)點的結(jié)構(gòu)體 TreeNode
,并實現(xiàn)了層次遍歷方法 levelOrder
。在 main
函數(shù)中,我們創(chuàng)建了一棵樹并調(diào)用 levelOrder
方法進行層次遍歷。運行結(jié)果將輸出樹節(jié)點的值的層次遍歷順序。