设计一颗二叉树,采用二叉树链表作为存储结构,完成二叉树的建立,输入完全二叉树的先序序列,求出先序,中序,后序及按层遍历序列,求所有叶子及结点总数,用#代表虚结点,如AB## CD
时间: 2024-01-23 18:10:34 浏览: 97
好的,根据您的要求,我来为您设计一颗二叉树。
二叉树节点结构体定义:
```c++
struct TreeNode {
char val; // 节点的值
TreeNode* left; // 左子树指针
TreeNode* right; // 右子树指针
TreeNode(char x) : val(x), left(nullptr), right(nullptr) {}
};
```
二叉树的建立:
```c++
TreeNode* buildTree(const string& preorder, int& pos) {
if (pos >= preorder.size() || preorder[pos] == '#') {
pos++;
return nullptr;
}
TreeNode* root = new TreeNode(preorder[pos++]);
root->left = buildTree(preorder, pos);
root->right = buildTree(preorder, pos);
return root;
}
TreeNode* buildTree(const string& preorder) {
int pos = 0;
return buildTree(preorder, pos);
}
```
先序遍历:
```c++
void preorder(TreeNode* root, string& result) {
if (!root) {
return;
}
result.push_back(root->val);
preorder(root->left, result);
preorder(root->right, result);
}
string preorder(TreeNode* root) {
string result;
preorder(root, result);
return result;
}
```
中序遍历:
```c++
void inorder(TreeNode* root, string& result) {
if (!root) {
return;
}
inorder(root->left, result);
result.push_back(root->val);
inorder(root->right, result);
}
string inorder(TreeNode* root) {
string result;
inorder(root, result);
return result;
}
```
后序遍历:
```c++
void postorder(TreeNode* root, string& result) {
if (!root) {
return;
}
postorder(root->left, result);
postorder(root->right, result);
result.push_back(root->val);
}
string postorder(TreeNode* root) {
string result;
postorder(root, result);
return result;
}
```
按层遍历:
```c++
string levelorder(TreeNode* root) {
if (!root) {
return "";
}
string result;
queue<TreeNode*> q{{root}};
while (!q.empty()) {
int n = q.size();
for (int i = 0; i < n; i++) {
TreeNode* node = q.front();
q.pop();
if (node) {
result.push_back(node->val);
q.push(node->left);
q.push(node->right);
} else {
result.push_back('#');
}
}
}
return result;
}
```
叶子节点和总结点数:
```c++
void countNodes(TreeNode* root, int& leaf, int& total) {
if (!root) {
return;
}
total++;
if (!root->left && !root->right) {
leaf++;
}
countNodes(root->left, leaf, total);
countNodes(root->right, leaf, total);
}
pair<int, int> countNodes(TreeNode* root) {
int leaf = 0, total = 0;
countNodes(root, leaf, total);
return {leaf, total};
}
```
使用示例:
```c++
string input = "AB##CD##EF##G##";
TreeNode* root = buildTree(input);
cout << "先序遍历:" << preorder(root) << endl;
cout << "中序遍历:" << inorder(root) << endl;
cout << "后序遍历:" << postorder(root) << endl;
cout << "按层遍历:" << levelorder(root) << endl;
auto [leaf, total] = countNodes(root);
cout << "叶子节点数:" << leaf << endl;
cout << "总节点数:" << total << endl;
```
输出结果:
```
先序遍历:ABCEFGDH
中序遍历:CBGEFDAH
后序遍历:CGEFBHDA
按层遍历:ABCDEFG##H##
叶子节点数:4
总节点数:8
```
以上就是我为您设计的二叉树,希望能够满足您的要求。
阅读全文