二叉树实现堆,咕咕咕
1.
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef char BT;
typedef struct BTNode
{BT data;struct BTNode* left;struct BTNode* right;
}BTNode;
//已知一个数组arr
BTNode* BTtreecreate(BT* a,int n,int* p)
{//'#'表示空节点用p指针是因为接下来要调用函数,要用同一个p,并不是分开的pif(*p>=n||a[*p]=='#'){(*p)++;//移动到下一个位置return NULL;}BTNode* btnode=(BTNode*)malloc(sizeof(BTNode));assert(btnode!=NULL);btnode->data=a[*p];(*p)++;BTtreecreate(a,n,p);BTtreecreate(a,n,p);return btnode;
}
//销毁
void BTtreedestroy(BTNode** root)
{if(root==NULL||*root==NULL) return;BTtreedestroy(&((*root)->left));BTtreedestroy(&((*root)->right));free(*root);*root=NULL;
}
//节点个数
int BTnodesize(BTNode* root)
{if(root==NULL) return 0;return 1+BTnodesize(root->left)+BTnodesize(root->right);
}
//叶子的个数
int BTleavesize(BTNode* root)
{
if(root==NULL) return 0;
if(root->left==NULL&&root->right==NULL)
{return 1;
}
return BTleavesize(root->left)+BTleavesize(root->right);
}
//第k层结点的个数
int BTksize(BTNode* root,int k)
{
if(root==NULL||k<=0) return 0;
if(k==1) return 1;
return BTksize(root->left,k-1)+BTksize(root->right,k-1);
}
//找x的结点
BTNode* BTfindx(BTNode* root,BT x)
{if(root==NULL) return NULL;if(root->data==x) return root;BTNode* leftresult=BTfindx(root->left,x);if(leftresult!=NULL) return leftresult;return BTfindx(BTNode* root->right);
}
//二叉树前序遍历
void BTpreorder(BTNode* root)
{if(root==NULL) return;printf("%c",root->data);BTpreorder(root->left);BTpreorder(root->right);
}
//二叉树中序遍历
void BTinorder(BTNode* root)
{if(root==NULL) return;BTinorder(root->left);printf("%c",root->data);BTinorder(root->right);
}
//二叉树后序遍历
void BTpostorder(BTNode* root)
{if(root==NULL) return;BTpostorder(root->left);BTpostorder(root->right);printf("%c",root->data);
}
//层序遍历
void BTlevelorder(BTNode* root)
{if(root==NULL) return;Queue q;QueueInit(q);Queuepush(&q,root);while(!Queueempty(q)){BTNode* current=QueuePop(&q);printf("%c",current->data);if(current->left!=NULL) Queuepush(&q,current->left);if(current->right!=NULL)Queuepush(&q,current->right);}
}
//判断是否完全二叉树
int iscomplete(BTNode* root)
{//根结点先入队列,保证队列不为空//循环判断队列是否为空,不为空取对头,出对头,把对头结点的左右孩子全部入队列//取到空的对头,跳出循环,判断剩下是否全部为空结点Queue q;QueueInit(q);Queupush(&q,root);while(!QueueEmpty(&q)){BTNode* top=QueueFront(&q);QueuePop(&q);if(top==NULL){break;}Queuepush(&q,top->left);Queuepush(&q,top->right);}
while(!QueueEmpty(&q))
{BTNode* top=QueueFront(&q);QueuePop(&q);if(top!=NULL){QueueDestroy(&q);return false;}
}
QueueDestroy(&q);
return true;
}
2.二叉树的题目(未完待续)
性质:二叉树0度结点n0个,2度结点n2个,则n0=n2+1
(a个2度,b个1度,c个0度(叶节点),边数2a+b(所有的子节点数,度数代表子节点数),边数也是a+b+c-1(总结点数-1),所以a=c-1)