输入二叉树的广义表形式建立二叉树+C++


广义表形式的二叉树输入,形如:A(B(C(,),F),G(H,I))。即为前序遍历格式

程序假设输入无空格,每个节点使用一个字母表示使用递归和状态机来进行处理

// Author: Haiping Huang
// Assume input contains no white space and each node is represented by one character
// read console input or "./in.txt" (toggle by macro: READFILE)
// Sample input: A(B(C(,),F),G(H,I))
//

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

typedef struct BiTNode
{
	char data;
	struct BiTNode* lchild, *rchild;
} BiTNode, *BiTNodePtr;

BiTNode* CreateBiTNode()
{
	BiTNode* node = (BiTNode*) malloc(sizeof(BiTNode));
	node->data = 0;
	node->lchild = node->rchild = NULL;
	return node;
}

void FreeBiTNode(BiTNode* node)
{
	free(node);
}

// test function
void PreOrderTraverse(const BiTNode* root)
{
	if (root)
	{
		printf("%c", root->data);
		PreOrderTraverse(root->lchild);
		PreOrderTraverse(root->rchild);
	}
}

BiTNode* _createTree(char** p)
{
	BiTNode* root = NULL;

	if (isalpha(**p))
	{
		root = CreateBiTNode();
		root->data = **p;
		++(*p);
	} 
	if (**p == '(')
	{
		++(*p);
		if (root)
		{
			root->lchild = _createTree(p);
		}
		else
		{
			printf("Error input!");
			exit(1);
		}
	}
	else
	{
		// quit recursive event
		return root;
	}

	if (**p == ',')
	{
		++(*p);
		if (root)
		{
			root->rchild = _createTree(p);
		}
		else
		{
			printf("Error input!");
			exit(1);
		}
	}
	else
	{
		printf("Error input!");
		exit(1);
	}

	if (**p == ')')
	{
		++(*p);
		return root;
	}
	else
	{
		printf("Error input!");
		exit(1);
	}
	return root;
}

BiTNode* CreateBiTree(char* input)
{
	char* p = input;
	return _createTree(&p);
}

int main(int argc, char* argv[])
{
	FILE* in;
#ifdef READFILE
	in = fopen("in.txt", "r");
#else
	in = stdin;
#endif

	char input[512];
	fscanf(in, "%s", input);

	BiTNode* root = CreateBiTree(input);
	PreOrderTraverse(root);

	return 0;
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值