遞歸創建和輸出M叉樹

 M 叉樹採用列表法表示,即每棵子樹對應一個列表,列表的結構爲:子樹根結點的值部分 (設爲一個字符和用“( )”,括起來的各子樹的列表 (如有子樹的話) ,各子列表間用“,”,分隔。例如下面的三叉樹可用列表 a( b( c,d ),e,f( g,h,i ))表示。

#include<iostream>
//#include<stdio.h>

using namespace std;

#define M 3

typedef struct node{
	char val;
	struct node* subTree[M];
}NODE;

char buf[255],*str = buf;
NODE * d = NULL;

NODE * makeTree()
{
	int k;
	NODE *s;
	s = new NODE();
	s->val = *str++;
	for(k=0;k<M;k++)
	{
		s->subTree[k] = NULL;
	}
	if(*str=='(')
	{
		k = 0;
		do{
			str++;
			s->subTree[k] = makeTree();
			if(*str==')'){
				str++;
				break;
			}
			k = k + 1;
		}while(k<M);
	}
	return s;
}

void walkTree(NODE * t)
{
	if(t!=NULL){
		cout<<t->val;
		if(t->subTree[0]==NULL)
			return ;
		cout <<"("; 
		for(int i=0;i<M;i++){
			walkTree(t->subTree[i]);
			if(i!=M-1&&t->subTree[i+1]!=NULL)
				cout << ',';
		}
		cout << ')';
	}
}

int main()
{
	cout << "Enter exp: ";
	cin >> str;
	d = makeTree();
	walkTree(d);
	cout << endl;
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章