【二叉树】普通二叉树的 建立和遍历

二叉树的建立和遍历还是主要是递归调用的问题。

static DoubleTree CreateTree()
{
	int ch;
	DoubleTree tree = NULL;
	scanf("%d", &ch);
	if(ch==0){
		tree = NULL;
	}else{
		tree = (DoubleTree)malloc(sizeof(struct DoubleTreeNode));
		if(tree==NULL){
			fprintf(stderr, "there is no space\n");
			return NULL;
		}
		tree->element = ch;
		tree->LeftNode = CreateTree();//会先将所有的左子树建立好
		tree->RightNode = CreateTree();//递归补充又子树
	}
	return tree;
}

我奇怪的是传入的DoubleTree tree这个指针,结果传出来的还是NULL

static void CreateTree(DoubleTree tree)
{
	int ch;
	//DoubleTree tree = NULL;
	scanf("%d", &ch);
	if(ch==0){
		tree = NULL;
	}else{
		tree = (DoubleTree)malloc(sizeof(struct DoubleTreeNode));
		if(tree==NULL){
			fprintf(stderr, "there is no space\n");
			return;
		}
		tree->element = ch;
		CreateTree(tree->LeftNode);//会先将所有的左子树建立好
		CreateTree(tree->RightNode);//递归补充又子树
	}
	return;
}

这个应该和函数传入的参数有关,先暂时放在这里

-------------------------------------------------------------------------------------


普通二叉树的先序遍历(头-->左--->右)

void PreTraverse(DoubleTree tree)
{
	if(tree){
		printf("%d\n", tree->element);
		PreTraverse(tree->LeftNode);
		PreTraverse(tree->RightNode);
	}
	return;
}


中序遍历(左--->中--->右)

static void MidTraverse(DoubleTree tree)
{
	if(tree){
		MidTraverse(tree->LeftNode);
		printf("%d\n", tree->element);
		MidTraverse(tree->RightNode);
	}
	return;
}


后序遍历(左--->右---->中)

static void LastTravese(DoubleTree tree)
{
	if(tree){
		LastTravese(tree->LeftNode);
		LastTravese(tree->RightNode);
		printf("%d\n", tree->element);
	}
	return ;
}

猜你喜欢

转载自blog.csdn.net/feifei_csdn/article/details/80156807