创建二叉树(括号表示法)

void CreateBTree(BTNode*& b, char* str)
{
	BTNode* St[MAXSIZE];
	int top = -1;
	BTNode* p;
	char ch = *str;
	b = NULL;
	int k;
	while (ch != '\0')
	{
		switch (ch)
		{
		case'(':
			St[++top] = p;
			k = 1;
			break;
		case')':
			top--;
			break;
		case',':
			k = 2;
			break;
		default:
			p = (BTNode*)malloc(sizeof(BTNode));
			p->data = ch;
			p->lchild = p->rchild = NULL;
			if (b == NULL)
				b = p;
			else
			{
				switch (k)
				{
				case 1:St[top]->lchild = p; break;
				case 2:St[top]->rchild = p; break;
				}
				break;
			}
		}
		ch = *(++str);
	}
}

  

void DispBTree(BTNode* b)
{
	if (b != NULL)
	{
		printf("%c ", b->data);
		if (b->lchild != NULL || b->rchild != NULL)
		{
			printf("(");
			DispBTree(b->lchild);
			if (b->rchild != NULL)
				printf(",");
			DispBTree(b->rchild);
			printf(")");
		}
	}
}

  

上一篇:Binary Tree


下一篇:数据结构:第五章学习小结