以字符串的形式定义一棵二叉树的先序序列,若字符是‘#’, 表示该二叉树是空树,否则该字符是相应结点的数据元素。读入相应先序序列,建立二叉树,然后按层次遍历该二叉树并输出结点数据。
时间: 2023-04-27 19:01:16 浏览: 193
首先,我们可以定义一个二叉树节点的结构体,包含数据元素和左右子节点指针:
```
struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x) : val(x), left(NULL), right(NULL) {}
};
```
然后,我们可以定义一个递归函数来建立二叉树:
```
TreeNode* buildTree(string& s, int& index) {
if (index >= s.size() || s[index] == '#') {
index++;
return NULL;
}
TreeNode* root = new TreeNode(s[index++]);
root->left = buildTree(s, index);
root->right = buildTree(s, index);
return root;
}
```
最后,我们可以使用队列来进行层次遍历,并输出每个节点的数据元素:
```
void levelOrder(TreeNode* root) {
if (!root) return;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
cout << node->val << " ";
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
```
完整代码如下:
```
#include <iostream>
#include <string>
#include <queue>
using namespace std;
struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* buildTree(string& s, int& index) {
if (index >= s.size() || s[index] == '#') {
index++;
return NULL;
}
TreeNode* root = new TreeNode(s[index++]);
root->left = buildTree(s, index);
root->right = buildTree(s, index);
return root;
}
void levelOrder(TreeNode* root) {
if (!root) return;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
cout << node->val << " ";
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
int main() {
string s;
cin >> s;
int index = ;
TreeNode* root = buildTree(s, index);
levelOrder(root);
return ;
}
```
阅读全文