1概念
一棵二叉树是结点的一个有限集合,该集合
:
1.
或者为空
2.
由一个根节点加上两棵别称为左子树和右子树的二叉树组成
2特殊二叉树
1.
满二叉树
:一个二叉树,如果每一个层的结点数都达到最大值,则这个二叉树就是满二叉树。也就是
说,如果一个二叉树的层数为
K
,且结点总数是
,则它就是满二叉树。
2.
完全二叉树
:完全二叉树是效率很高的数据结构,完全二叉树是由满二叉树而引出来的。对于深度为
K
的,有
n
个结点的二叉树,当且仅当其每一个结点都与深度为
K
的满二叉树中编号从
1
至
n
的结点一一对
应时称之为完全二叉树。 要注意的是满二叉树是一种特殊的完全二叉树。
代码实现
创造树的结构
typedef struct BTtree
{
struct BTtree* left;
struct BTtree* right;
int val;
}BT;
个个函数的实现
//创造一个二叉树结点
BT* Buynode(int x)
{
BT* node = (BT*)malloc(sizeof(BT));
node->val = x;
node->left = NULL;
node->right = NULL;
return node;
}
//前序
void Preordeer(BT* root)
{
if (root == NULL)
{
printf("NULL ");
return;
}
printf("%d ", root->val);
Preordeer(root->left);
Preordeer(root->right);
}
//中序
void inorder(BT* root)
{
if(root == NULL)
{
printf("NULL ");
return;
}
inorder(root->left);
printf("%d ", root->val);
inorder(root->right);
}
//后序
void postorder(BT* root)
{
if (root == NULL)
{
printf("NULL ");
return;
}
postorder(root->left);
postorder(root->right);
printf("%d ",root->val);
}
//销毁
void treedestroy(BT* root)
{
if (root == NULL)
return;
treedestroy(root->left);
treedestroy(root->right);
free(root);
}
//计算节点树
int BinaryTreeSize(BT* root)
{
if (root == NULL)
return 0;
return BinaryTreeSize(root->left) + BinaryTreeSize(root->right) + 1;
}
//查找
BT* treefind(BT* root, int x)
{
if (root == NULL)
return NULL;
if (root->val == x)
return root;
BT* tem = treefind(root->left, x);
if (tem)
return tem;
tem = treefind(root->right, x);
if (tem)
return tem;
}
int max(int a, int b)
{
return a > b ? a : b;
}
//计算树的深度
int depth(BT* root)
{
if (root == NULL)
return 0;
return max(depth(root->left)+1,depth(root->right)+1);
}
int maxDepth(BT* root) {
return depth(root);
}
//计算叶子节点
int BinaryTreeLeafSize(BT* root)
{
if (!root)
return 0;
if (!root->left && !root->right)
return 1;
return BinaryTreeLeafSize(root->left) + BinaryTreeLeafSize(root->right);
}
//计算第k层节点数
int BinaryTreeLevelKSize(BT* root, int k)
{
if (root == 0 || k < 1)
return 0;
if (k == 1)
return 1;
return BinaryTreeLevelKSize(root->left, k - 1) + BinaryTreeLevelKSize(root->right, k - 1);
}
//层序
void BinaryTreeLevelOrder(BT* root)
{
queue<BT*>q;
q.push(root);
while (!q.empty())
{
BT* r = q.front();
q.pop();
cout << r->val;
if(r->left)
q.push(r->left);
if(r->right)
q.push(r->right);
}
}
//判断完全二叉树
bool BinaryTreeComplete(BT* root)
{
if (!root)
return true;
queue<BT*>q;
q.push(root);
while (!q.empty())
{
BT* r = q.front();
q.pop();
if (!r)
break;
q.push(r->left);
q.push(r->right);
}
while (!q.empty())
{
BT* r = q.front();
q.pop();
if(r)
{
return false;
}
}
return true;
}