广义表创建二叉树及二叉树输出广义表
时间: 2025-05-23 07:10:12 浏览: 21
### C++ 中广义表与二叉树的转换
#### 1. 广义表创建二叉树
在 C++ 中,可以通过解析广义表字符串来构建二叉树。广义表是一种递归的数据结构,通常用于描述嵌套关系。对于二叉树而言,其广义表表示法遵循以下规则:
- 如果某个子节点为空,则用 `#` 表示。
- 子节点之间用逗号分隔,左子树先于右子树。
以下是基于模板类实现的一个简单例子:
```cpp
#include <iostream>
#include <stack>
using namespace std;
template<typename DataType>
struct BTNode {
DataType value;
BTNode<DataType> *lchild, *rchild;
explicit BTNode(DataType x) : value(x), lchild(nullptr), rchild(nullptr) {}
};
// 解析函数:将广义表转化为二叉树
template<typename DataType>
BTNode<DataType>* createBinaryTree(const string& expr, int& index) {
if (index >= expr.size()) return nullptr;
char ch = expr[index];
if (ch == '#') { // 空节点
++index;
return nullptr;
}
// 构建根节点
BTNode<DataType>* root = new BTNode<DataType>(expr[index]);
++index; // 跳过当前字符
if (index < expr.size() && expr[index] == '(') { // 左子树开始
++index; // 跳过'('
root->lchild = createBinaryTree(expr, index);
if (expr[index] == ')') { // 右子树结束标志
++index; // 跳过')'
} else { // 继续读取右子树
root->rchild = createBinaryTree(expr, index);
if (expr[index] == ')') {
++index; // 跳过')'
}
}
}
return root;
}
```
此代码片段展示了如何通过递归调用来解析广义表并构建二叉树[^2]。
---
#### 2. 将二叉树输出为广义表
为了将二叉树以广义表的形式打印出来,可以采用前序遍历的方式。具体逻辑如下:
- 若当前节点为空,则返回 `"#"`;
- 否则依次访问根节点、左子树和右子树;
- 对于非空子树,在值前后加上括号 `( ... )` 来区分层次。
下面是具体的实现代码:
```cpp
template<typename DataType>
void printAsGeneralizedList(BTNode<DataType>* root) {
if (!root) {
cout << "#";
return;
}
cout << root->value; // 打印当前节点值
if (root->lchild || root->rchild) { // 至少有一个子节点不为空
cout << "(";
printAsGeneralizedList(root->lchild); // 打印左子树
if (root->rchild) { // 如果右子树存在
cout << ",";
printAsGeneralizedList(root->rchild); // 打印右子树
}
cout << ")";
}
}
int main() {
string generalizedExpr = "A(B(D,#),C(#,F(G,#)))"; // 输入广义表
int index = 0;
auto* treeRoot = createBinaryTree<char>(generalizedExpr, index);
cout << "Generated Binary Tree as Generalized List: ";
printAsGeneralizedList(treeRoot);
cout << endl;
return 0;
}
```
这段代码实现了从输入的广义表到二叉树的转化,并最终再次输出为广义表形式[^4]。
---
####
阅读全文
相关推荐
















