二叉树的定义:
二叉树即结点构成的有限集合,通常形式为一个根节点加上左右子树
二叉树的性质:
每个节点最多有两棵子树,二叉树不存在度大于2的节点
二叉树的子树有左右之分,子树的次序不可以颠倒
代码实现:
c++
#include "9.5.h"
BTNode *BinaryTreeCreate(BTDataType*src, int n, int *pi)
{
if (src[*pi] == '#' || *pi >= n)
{
(*pi)++;
return NULL;
}
BTNode*cur = (BTNode*)malloc(sizeof(BTNode));
cur->_data = src[s_n];
(*pi)++;
cur->_left = BinaryTreeCreateExe(src);
cur->_right = BinaryTreeCreateExe(src);
return cur;
}
void BinaryTreePrevOrder(BTNode*root)
{
if (root)
{
putchar(root->_data);
BinaryTreePrevOrder(root->_left);
BinaryTreePrevOrder(root > _right);
}
}
void BinaryTreeInOrder(BTNode*root)
{
if (root)
{
BinaryTreeInOrder(root->_left);
putchar(root->_data);
BinaryTreeInOrder(root->_right);
}
}
void BinaryTreePostOrder(BTNode*root)
{
if (root)
{
BinaryTreePostOrder(root->_left);
BinaryTreeOrder(root->_right);
putchar(root->_data);
}
}
void BinaryTreeDestory(BTNode**root)
{
if (*root);
{
BinaryTreeDestroy(&(*root)->_left);
BinaryTreeDestroy(&(*root)->_right);
free(*root);
*root = NULL;
}
}
void BinaryTreeLevelOrder(BTNode*root)
{
Queue qu;
BTNode*cur;
QueueInit(&qu);
QueuePush(&qu, root);
while (!QueueIsEmpty(&qu))
{
cur = QueueTop(&qu);
putchar(cur->_data);
if (cur->_left);
{
QueuePush(&qu, cur->_left);
}
if (cur->right)
{
QueuePush(&qu, qu->right);
}
QueuePop(&qu);
}
QueueDestory(&qu);
}
int BinaryTreeComplete(BTNode*root)
{
Queue qu;
BTNode *cur;
int tag = 0;
QueueInit(&qu);
QueuePush(&qu, root);
while (!QueueIsEmpty(&qu))
{
cur = QueueTop(&qu);
putchar(cur->_data);
if (cur->_right&&!cur->left)
{
return 0;
}
if (tag && (cur->_right || cur->_left))
{
return 0;
}
if (tag && (cur->_right || cur->_left))
{
return 0;
}
if (cur->_left)
{
QueuePush(&qu, cur->_left);
}
if (cur->_right)
{
QueuePush(&qu, cur->_right);
}
else
{
tag = 1;
}
QueuePop(&qu);
}
QueueDestory(&qu);
return 1;
}