全部代码:
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
struct Node
{
char data;
struct Node* lchild, *rsibling;
};
void createCSTree_gen(Node *&root,string G) //创建树
{
if(G.length() <= 0)
{
root = NULL;
return;
}
struct SNode
{
Node *ptr;
int dir; //dir = 0,左链,dir = 1,右链
};
const int stackSize = 20; //这里用数组当栈下面方便点
SNode stk[stackSize]; int top = -1; //栈,置空
root = new Node();
root->data = G[0]; root->lchild = root->rsibling = NULL;
stk[++top].ptr = root; //根指针进栈
Node* p;
char ch;
for(int i = 1; i < G.length(); i++)
{
ch = G[i];
switch(ch)
{
case '(':stk[top].dir = 0; break; //下一个结点为左子女
case ')':top--; break;
case ',':stk[top].dir = 1; break; //下一个结点为右兄弟
default:
p = new Node(); //新结点
p->data = ch; p->lchild = p->rsibling = NULL;
if(top > -1) //非根结点
{
if(stk[top].dir == 0) //作为左子女链接
stk[top].ptr->lchild = p;
else //作为右兄弟链接
{
stk[top].ptr->rsibling = p;
top--;
}
}
stk[++top].ptr = p;
}
}
}
void printChildAndSiblingTree(Node *root, int k) // 打印树
{
if (root != NULL)
{
for (int i = 0; i < k; i++) cout << " "; // 右移k个字符
cout << root->data << endl; //输出根结点data
for (Node * p = root->lchild; p != NULL; p = p->rsibling)
{
printChildAndSiblingTree(p, k + 5); //输出根的子树
}
}
}
int main()
{
string G = "A(B(E(K,L),F),C(G),D(H(M),I,J))"; //广义表
Node *root = NULL;
createCSTree_gen(root,G);
printChildAndSiblingTree(root,0);
return 0;
}