纯C创建二叉树及二叉树的遍历

2 篇文章 0 订阅

代码如下:

#include <stdio.h>
#include <malloc.h>
typedef struct TreeNode Tree;
struct TreeNode{
	int value;
	int level;//level
	Tree *leftChild;
	Tree *rightChild;
	Tree *parent;
};
Tree *SetChild(int value,Tree *parentT);//ok 
void View_Tree(Tree *pThis);//ok
void mk_space(int nums);
int main()
{
	Tree *k;
	Tree *moveon;
	//Tree *t;
	int inValue=0,c_val=0;
	//creat a tree(init k)
	k=(Tree *)malloc(sizeof(Tree));//k as top,do not change
	k->parent=NULL;//the top point has no parent
	k->level=0;
	moveon=k;//save k's location for use
	printf("input the value of the first item:");
	scanf("%d",&inValue);
	moveon->value=inValue;
	while(inValue>0 || c_val!=4)
	{
		printf("input left value of %d:",moveon->value);
		scanf("%d",&inValue);//set value
		if(inValue>0)
			moveon->leftChild=SetChild(inValue,moveon);
		printf("input right value of %d:",moveon->value);
		scanf("%d",&inValue);
		if(inValue>0)
			moveon->rightChild=SetChild(inValue,moveon);
		printf("next?\nif go up,input 1\nif go to left child,input 2\nif goto right child,input 3\nif exit,input 4\ninput:");
		scanf("%d",&c_val);
		if(c_val==1){
			if(moveon->parent==NULL) break;
			moveon=moveon->parent;
		}else if(c_val==2){
			moveon=moveon->leftChild;
		}
		else if(c_val==3){
			moveon=moveon->rightChild;
		}
		else if(c_val==4){
			break;//跳出循环
		}
	}
	if(inValue==0) return 0;
	//开始遍历
	View_Tree(k);

	free(k);
}
Tree *SetChild(int value,Tree *parentT)//ok 
{
	Tree *ks=(Tree *)malloc(sizeof(Tree));
	ks->value=value;//set value
	ks->parent=parentT;//set parent point to go back
	ks->leftChild=NULL;//left and
	ks->rightChild=NULL;//right are set null
	ks->level=parentT->level+1;
	return ks;
}
void View_Tree(Tree *pThis)
{
	mk_space(pThis->level);
	printf("%d\n",pThis->value);
	if(pThis->leftChild!=NULL)
	{
		View_Tree(pThis->leftChild);
	}
	if(pThis->rightChild!=NULL)
	{
		View_Tree(pThis->rightChild);
	}
}
void mk_space(int nums)
{
	int k;
	for(k=0;k<nums*2;k++)
	{
		printf(" ");
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值