二叉树的一些基本操作
本章包含了二叉树的一些基本操作:创作节点,创建树的过程,前序遍历,拷贝树,求树的节点,叶子的个数,树的深度,查找树的节点,插入树的节点,删除树的节点.(借鉴网上不少的例子)
首先是定义节点
typedef struct BTtree
{
int key;
struct BTtree*left,*right;
}BT;
第二是创建书的根节点(因为这个创建树的节点,导致我创建树的过程有瑕疵,所以我用来一个全局变量来补救)
BT*creatroot()
{
BT*tree=(BT*)malloc(sizeof(BT));
scanf("%d",&tree->key);
tree->left=NULL;
tree->right=NULL;
return tree;
}
创建树根的子节点(此处参考趣学数据结构的方法,用询问法来创立节点)
BT*creattree(BT*tree)
{
char check;
if(n>1)//此处n是全局变量
{
BT*tree=(BT*)malloc(sizeof(BT));
printf("请输入节点信息");
getchar()//防止回车键跳过scanf函数
scanf("%d",&tree->key);
}
n++;//全局变量
printf("是否添加%d的左孩子(Y/N)"tree->key);
getchar();//防止回车键跳过scanf函数
scanf("%c",&check);
if(check=='Y')
tree->left=creattree(tree->left);//应该是有返回值,才能连接在一起
else
tree->left=NULL;
printf("是否添加%d的右孩子(Y/N)"tree->key);
getchar(); //防止回车键跳过scanf函数
scnanf("%c",&check);
if(chekc=='N')
tree->right=creattree(tree->right);
return tree;
}
前序遍历(递归法)
void preorder(BT*tree)
{
if(tree)//在树空的情况
{
printf("%d",tree->key);
if(tree->left);
preorder(tree->left);
if(tree->right)
preorder(tree->right);
}
}
拷贝树
BT*copy(BT*tree)
{
BT*temp=(BT)malloc(sizeof(BT));
if(tree)
temp=tree;
if(tree->left)
temp->left=copy(tree->left);
if(tree->right)
temp->right=copy(tree->right);
return temp;
}
求树的节点
int getNode(tree)
{
int count;
if(tree==NULL)
count=0;
else
count=1+getNode(tree->left)+getNode(tree->right);
return count;
}
求叶子的个数
int getleaves(BT*tree)
{
int count=0;
if(tree==NULL)
count=0;
else if(tree->left==NULL&&tree->right==NULL)
count=1;
else
count=getleaves(tree->left)+getleaves(right);
return count;
}
求树的深度
int deepoftree(BT*tree)
{
int right=0,left=0;
if(tree->left)
left=deepoftree(tree->left);
if(tree->right)
right=deepoftree(tree->right);
if(tree==NULL)
return 0;
return left>right?left+1:right+1;
}
查找树的节点
void check(BT*tree,int value)
{
if(tree->key>value)
check(tree->left,value);
if(tree->key<value)
check(tree->right,value);
if(tree->key==value)
printf("查找的节点时%d",tree->key);
}
插入树的节点
BT*insert(BT*tree,int value)
{
if(tree->key>value)
tree->left=insert(tree->left,value);
else if(tree->key<value)
tree->right=insert(tree->right,value);
else if(tree->key>value&&tree->left==NULL)
{
tree->left=(BT*)malloc(sizeof(BT));
tree->left->key=value;
}
else if(tree->key<value&&tree->lright==NULL)
{
tree->right=(BT*)malloc(sizeof(BT));
tree->right->key=value;
}
return tree;
}
删除树的节点
BT* del(BT* tree, int value)
{
BT* temp;
if (tree == NULL)
printf("要删除的元素未找到");
else if (value < tree->key)//左子树递归删除
tree->left = del(tree->left, value);
else if (value > tree->key)//右子树递归删除
tree->right = del(tree->right, value);
else//找到要删除的节点
{
if (tree->left && tree->right)//被删除的节点有左右两个子节点
{
temp = findmin(tree->right);//在右子树找到最小的元素删除最小元素
tree->key = temp->key;
tree->right = del(tree->right, tree->key);//在删除节点的右子树中找最小元素
}
else//
{
temp = tree;
if (tree->left == NULL)//有右孩子或无子节点
tree = tree->right;
else if (tree->right == NULL)//有左孩子或无子节点
tree = tree->left;
free(temp);
}
}
return tree;
}