#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node*lchild;//左链域
struct node*rchild;//右链域
};
typedef node BiTNode;
typedef node* BiTree;
//初始化根节点
BiTree Init_Tree(BiTNode*root)
{
BiTree tree = root;
return tree;
}
//制造节点 4
BiTNode*MakeNode(int data,BiTNode*lchild,BiTNode*rchild)
{
BiTNode*temp = (BiTNode*)malloc(sizeof(BiTNode));
if(temp == NULL)
{
return NULL;
}
temp->data = data;
temp->lchild = lchild;
temp->rchild = rchild;
return temp;
}
//释放节点
void Free_Node(BiTNode*pnode)
{
if(pnode!=NULL)
{
free(pnode);
pnode = NULL;
}
}
//销毁树
void Destroy_Free(BiTree tree)
{
BiTNode*temp = tree;
if(temp->lchild!=NULL)
{
Destroy_Free(temp->lchild);
}
if(temp->rchild!=NULL)
{
Destroy_Free(temp->rchild);
}
Free_Node(temp);
}
//判断树是否为空
int Empty_Free(BiTree tree)
{
if(tree==NULL)
{
return 0;
}
else
{
return 1;
}
}
//2
//求树的深度
int GetDepth(BiTree tree)
{
int left;
int right;
if(tree==NULL)
{
return 0;
}
left = GetDepth(tree->lchild);
right = GetDepth(tree->rchild);
return left>right?(left+1):(right+1);
}
//获取的树的根节点
BiTree Get_Free(BiTree tree)
{
return tree;
}
//获取的树的节点
int Get_Node(BiTNode*node)
{
return node->data;
}
//设置的树的节点
void Set_Node(BiTNode*node,int data)
{
node->data = data;
}
//设置的树的左孩子
BiTNode* Set_lchild(BiTNode*node,BiTNode*lchild)
{
node->lchild = lchild;
return lchild;
}
//获取的树的左孩子
BiTNode* Get_lchild(BiTNode*tree)
{
if(tree==NULL)
{
return NULL;
}
return tree->lchild;
}
//设置的树的右孩子
BiTNode* Set_rchild(BiTNode*node,BiTNode*rchild)
{
node->rchild = rchild;
return rchild;
}
//获取的树的右孩子
BiTNode* Get_rchild(BiTNode*tree)
{
if(tree==NULL)
{
return NULL;
}
return tree->rchild;
}
//插入子树
BiTree Insert_Child(BiTNode*parent,int lr,BiTNode*child)
{
if(parent)
{
if(parent->lchild==NULL&&lr == 0)
{
parent->lchild = child;
return child;
}
if(parent->rchild==NULL&&lr == 1)
{
parent->rchild = child;
return child;
}
}
return NULL;
}
//删除子树
void DeleteChild(BiTNode*parent,int lr)
{
if(parent)
{
if(parent->lchild!=NULL&&lr==0)
{
parent->lchild = NULL;
Free_Node(parent->lchild);
}
if(parent->rchild!=NULL&&lr==1)
{
parent->rchild = NULL;
Free_Node(parent->rchild);
}
}
}
void ahead(BiTNode*head)
{
if(head!=NULL)
{
ahead(head->lchild);
printf("%d\n",head->data);
ahead(head->rchild);
}
}
int main()
{
BiTNode*n1 = MakeNode(7,NULL,NULL);
BiTNode*n2 = MakeNode(6,NULL,NULL);
BiTNode*n3 = MakeNode(9,n1,n2);
BiTNode*n4 = MakeNode(5,NULL,NULL);
BiTNode*n5 = MakeNode(4,NULL,NULL);
BiTNode*n6 = MakeNode(8,n4,n5);
BiTNode*n7 = MakeNode(10,n3,n6);
BiTree tree = Init_Tree(n7);
//printf("root :%d\n",tree->data);
//printf("dep:%d\n",GetDepth(n7));
//DeleteChild(n7,0);
//BiTNode*n9 = MakeNode(200,NULL,NULL);
//BiTNode*n10 = MakeNode(300,NULL,NULL);
//BiTNode*n8 = MakeNode(100,n9,n10);
//Insert_Child(n7,0,n8);
ahead(n7);
system("pause");
return 0;
}
树
最新推荐文章于 2024-05-14 17:05:40 发布