【表达式树】后序表达式构造表达式二叉树

之前在栈的数据结构中有见到将中序表达式转换成后序表达式的方法,现在来看看如何用后序表达式构造一个表达式二叉树

static DoubleTree CreatExpressTree(char *express)
{
	unsigned int len = strlen(express);
	DoubleTree statck[len];//C99允许数组的大小为变量
	int top = 0;
	for(char *p=express; p!=express+len;p++){
		DoubleTree tree = (DoubleTree)malloc(sizeof(struct DoubleTreeNode));
		if(tree==NULL){
			fprintf(stderr,"%s: there is no space", __func__);
			return NULL;
		}
		if(*p=='+'||*p=='-'||*p=='*'||*p=='/'){
			DoubleTree tree_right = statck[--top];
			DoubleTree tree_left = statck[--top];
			statck[top] = tree;
			statck[top]->element = *p;
			statck[top]->LeftNode = tree_left;
			statck[top]->RightNode = tree_right;
			
		}else{
			statck[top] = tree;
			statck[top]->element = *p;
			statck[top]->LeftNode = NULL;
			statck[top]->RightNode = NULL;
		}
		top++;
	}
	return statck[0];
}

使用后续遍历可以打印出这个数据,这里使用数组来实现。

static void LastOverview(DoubleTree tree)
{
	if(tree){
		LastOverview(tree->LeftNode);
		LastOverview(tree->RightNode);
		printf("%c ", tree->element);
	}
	return;
}

main函数中的调用

DoubleTree tree = NULL;
char express[] = "ab+cde+**";
tree = CreatExpressTree(express);
LastOverview(tree);

你可能感兴趣的:(基础知识)