#include<iostream>using namespace std;struct TreeNode{ int val; TreeNode* left; TreeNode* right; TreeNode(int v): val(v), left(NULL), right(NULL) {}};TreeNode* buildTree(){ int val; cin >> val; if(val == -1) // 空节点 return NULL; TreeNode* root = new TreeNode(val); root->left = buildTree(); root->right = buildTree(); return root;}int main(){ cout << "请输入二叉树的先序遍历序列(空节点用-1表示):" << endl; TreeNode* root = buildTree(); return 0;}用层次遍历该二叉树
时间: 2024-01-27 13:03:57 浏览: 117
可以使用队列来实现二叉树的层次遍历。具体步骤如下:
1. 将根节点放入队列中。
2. 当队列不为空时,取出队首节点,输出其值,并将其左右子节点(如果存在)放入队列中。
3. 重复第2步,直到队列为空。
下面是代码实现:
```c++
#include<iostream>
#include<queue>
using namespace std;
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int v): val(v), left(NULL), right(NULL) {}
};
TreeNode* buildTree(){
int val;
cin >> val;
if(val == -1) // 空节点
return NULL;
TreeNode* root = new TreeNode(val);
root->left = buildTree();
root->right = buildTree();
return root;
}
void levelOrder(TreeNode* root){
if(root == NULL)
return;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
TreeNode* cur = q.front();
q.pop();
cout << cur->val << " ";
if(cur->left)
q.push(cur->left);
if(cur->right)
q.push(cur->right);
}
}
int main(){
cout << "请输入二叉树的先序遍历序列(空节点用-1表示):" << endl;
TreeNode* root = buildTree();
cout << "层次遍历结果为:" << endl;
levelOrder(root);
return 0;
}
```
如果输入的二叉树是这样的:
```
1
2
-1
-1
3
4
-1
-1
5
-1
-1
```
则输出的层次遍历结果为:
```
1 2 3 4 5
```
阅读全文