输入广义表建立子女兄弟链表示的树

全部代码:

#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;	
} 

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值