HDU1622—二叉树的层次遍历
时间: 2023-12-18 11:30:19 浏览: 46
<<引用[1]:#include <iostream> #include <queue> using namespace std; struct Node { int data; Node* left; Node* right; }; void levelOrder(Node* root) { if (root == NULL) return; queue<Node*> Q; Q.push(root); while (!Q.empty()) { Node* current = Q.front(); cout << current->data << " "; if (current->left != NULL) Q.push(current->left); if (current->right != NULL) Q.push(current->right); Q.pop(); } } int main() { Node* root = new Node(); root->data = 1; root->left = new Node(); root->right = new Node(); root->left->data = 2; root->right->data = 3; root->left->left = new Node(); root->left->right = new Node(); root->left->left->data = 4; root->left->right->data = 5; levelOrder(root); return 0; }。
请回答我或者给我介绍或演示一下: HDU1622—二叉树的层次遍历?
以下是二叉树的层次遍历的演示:
```cpp
#include <iostream>
#include <queue>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
};
void levelOrder(Node* root) {
if (root == NULL) return;
queue<Node*> Q;
Q.push(root);
while (!Q.empty()) {
Node* current = Q.front();
cout << current->data << " ";
if (current->left != NULL) Q.push(current->left);
if (current->right != NULL) Q.push(current->right);
Q.pop();
}
}
int main() {
Node* root = new Node();
root->data = 1;
root->left = new Node();
root->right = new Node();
root->left->data = 2;
root->right->data = 3;
root->left->left = new Node(); root->left->right = new Node();
root->left->left->data = 4;
root->left->right->data = 5;
levelOrder(root);
return 0;
}
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)